Search code examples
node.jsnext.jssession-cookies

Not being able to remove cookies on nextjs in production


I am creating an application in NextJs and I set the cookie authorization when the user make login:

res.setHeader("Set-Cookie", [
        cookie.serialize("authorization", `Bearer ${jwtGenerated}`, {
          httpOnly: true,
          secure: process.env.NODE_ENV !== "development",
          sameSite: true,
          maxAge: 60 * 60 * 12,
          path: "/",
        })
]);

This part of the code works perfectly, it sets the cookie in the browser. However when I log out, I make a request to the url /api/logout that executes this code:

import cookie from "cookie";

export default (req, res) => {
  res.setHeader("Set-Cookie", [
    cookie.serialize("authorization", "false", {
      httpOnly: true,
      secure: process.env.NODE_ENV !== "development",
      sameSite: true,
      maxAge: 5,
      path: "/",
    })
  ]);
  return res.status(200).json({ roles: null, auth: false });
};

however it seems that it does not work in production. When I'm at localhost it removes cookies and changes their value. However in production nothing is changed. The expiration remains the same, value and everything else. Am I doing something wrong? Is there any other way to remove this cookie when the user make logout?


Solution

  • Are you using Vercel as the deployment platform? This bug is caused because Next.js's serverless features always return a 304 Not Modified. Quite frankly I don't know why this happens on the server, but I believe that it has something to do with HTTP requests on Next.js's internals.

    In order to fix this problem, I made the logout request a POST request with a static key. This will prevent 304 Not Modified error from happening.

    import cookie from "cookie";
    
    export default (req, res) => {
      if (req.method !== 'POST') return res.status(405).json({ status: 'fail', message: 'Method not allowed here!' });
    
      if (req.body.key === 'static_key') {
        res.setHeader("Set-Cookie", [
          cookie.serialize("authorization", "false", {
            httpOnly: true,
            secure: process.env.NODE_ENV !== "development",
            sameSite: true,
            maxAge: 5,
            path: "/",
          })
        ]);
    
        return res.status(200).json({ roles: null, auth: false });
      }
    
      return res.status(400).json({ status: 'fail', message: 'Bad request happened!' });
    };