Next JS How can i set cookies in an api without errors?

Viewed 15

Next JS. I am trying to set some cookies in my /api/tokencheck endpoint. Here is a very simplified version of the code:

import { serialize } from 'cookie';

export default (req, res) => {
  /* I change this manually to simulate if a cookie is already set */
  let cookieexists = 'no';

  async function getToken() {
    const response = await fetch('https://getthetokenurl');
    const data = await response.json();
    return data.token;
  }

  if (cookieexists === 'no') {
    getToken().then((token) => {
      res.setHeader('Set-Cookie', serialize('token', token, { path: '/' }));
    });
    return res.status(200).end();
  } else {
    return res.status(200).end();
  }
};

I have tried a ton of variations as to where to put my return.res.status... code, and tried many different ways to return a success code, but depending on where I put the code I variously end up with either of the following errors:

"API resolved without sending a response for /api/checkguestytoken, this may result in stalled requests."

or

"unhandledRejection: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client"

I seem to have some gap in my knowledge about how the API works in Next JS because I cannot figure out how to just run the async function, get a result, set a couple of cookies and then exit with a 200. Could someone please tell me what I'm doing wrong?

1 Answers

Try to return after the Promise has been resolved:

getToken()
  .then((token) => {
    res.setHeader('Set-Cookie', serialize('token', token, { path: '/' }));
    return res.status(200).send('Success');
  })
  .catch((err) => {
    return res.status(400).send('Server error');
  });
Related