Matt Thomas
Matt Thomas

Reputation: 1115

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}`);
};

Upvotes: 1

Views: 4928

Answers (1)

Matt Thomas
Matt Thomas

Reputation: 1115

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}`);
};

Upvotes: 1

Related Questions