Search code examples
herokunext.jsnestjsvercel

nextjs, cookie header not being set on redirect


I have a nextjs app I have deployed on vercel. It is paired with a nestjs back-end which is deployed in heroku.

I implemented login via github and, while developing the app, I used the following code to set a jwt header after the user successfully authenticated:

  @Get('redirect')
  @UseGuards(AuthGuard('github'))
  async githubAuthRedirect(@Req() req, @Res() res) {
    const accessToken = await this.authService.generateJWT(req.user);

    res.cookie('jwt', accessToken);
    res.redirect(`http://localhost:3000/dashboard`);
  }

That is the endpoint github calls once the user has approved access to their account.

That works while I run everything on localhost, but once I deployed the front-end app to vercel, the back-end app to heroku (and configured a CNAME alias for my api) then it doesn't work.

My server gets the request from github and the user is effectively redirected to the dashboard, but no cookie is set.

Am I doing something wrong? did I miss some vercel/nextjs configuration?


Solution

  • After some digging around and testing all the possible configurations, turns out this is not a problem with next or with nest (or with heroku or vercel).

    Cookies are by default set on the same domain which your request originates from, including sub domains.

    In my case this meant, my API was responding from api.[DOMAIN].com and the cookie was not reaching [DOMAIN].com.

    When setting the cookie I had to explicitely pass the parent domain:

    res.cookie('jwt', accessToken, {
            domain: 'scripthunt.sh',
            sameSite: 'none',
            secure: req.secure || req.headers['x-forwarded-proto'] === 'https',
          });
    

    You might need to change other settings on express like:

      app.enable('trust proxy');
      app.enableCors({
        origin: 'https://[MY DOMAIN].com',
        credentials: true,
      });
    

    Which might also be necessary for Heroku, not sure, all I know is my app now correctly sets the cookie.

    Cheers!