Search code examples
node.jsreactjsoauth-2.0next.js

Next.js API route can't set cookie


I cannot seem to get the seem to get the sever to send/set cookies on the client. When I open the developer and inspect the redirect, no cookies have been sent or set.

// pages/api/auth/github.ts
const handler: NextApiHandler = async (request, response) => {
  
  // Use request.query.code to fetch access token, ect.

  response.setHeader(
    'Set-Cookie',
    serialize('token', data.access_token, {
      path: '/',
    }),
  );

  response.redirect(`http://${request.headers.host}`);
};


Solution

  • I've added

    { sameSite: 'lax' } 
    

    to the cookie options and it works now.

    Full working example:

    // pages/api/auth/github.ts
    const handler: NextApiHandler = async (request, response) => {
      
      // Use request.query.code to fetch access token, ect.
    
      response.setHeader(
        'Set-Cookie',
        serialize('token', data.access_token, {
          path: '/',
          sameSite: 'lax'
        }),
      );
    
      response.redirect(`http://${request.headers.host}`);
    };