deployment

Cookies not being stored in browser after deploying web app to Vercel


I recently deployed my web application to Vercel, and I'm encountering an issue where cookies are not being stored in the browser after successful authentication using Google OAuth. Prior to deployment, when testing the application locally using localhost, the authentication flow worked as expected, and the session ID and email were successfully stored in the browser's cookie storage.

Here is the relevant code snippet for the authentication callback route:

// Callback URL for handling the Google Login response
router.get('/auth/callback', async (req, res) => {
const { code } = req.query;

if (!code) {
    return res.status(400).json({ message: 'Authorization code not provided' });
}

try {
  // Exchange authorization code for access token
  const tokenResponse = await axios.post(process.env.GOOGLE_TOKEN_ENDPOINT, null, {
    params: {
        client_id: process.env.GOOGLE_CLIENT_ID,
        client_secret: process.env.GOOGLE_CLIENT_SECRET,
        code,
        redirect_uri: process.env.AUTH_REDIRECT_URI,
        grant_type: 'authorization_code',
    }
});

  const accessToken = tokenResponse.data.access_token;     

  const userInfoResponse = await axios.get(process.env.GOOGLE_USER_INFO_ENDPOINT, {
    headers: {"Content-Type": "application/json", Authorization: `Bearer ${accessToken}`},
  });

  const userInfo = userInfoResponse.data;

  if(userInfo && userInfo.email) {
    res.cookie('email', userInfo.email, { domain: 'https://toggle-to-qb.vercel.app', path: '/', httpOnly: false, maxAge: 6 * 60 * 60 * 1000})
  }

  // Generate session token and set it as an HTTP-only cookie
  const sessionToken = googleAuth.generateSessionToken(userInfo);
  res.cookie('sessionId', sessionToken, { domain: "https://toggle-to-qb.vercel.app", path: '/',  httpOnly: true, maxAge: 6 * 60 * 60 * 1000 });
  res.redirect('https://toggle-to-qb.vercel.app/#/home');

} catch (error) {
  errorHandler.addError(error);
  console.error('Error:', error);
  res.status(500).json({ message: 'Internal Server Error' });
}finally{
  errorHandler.logErrors();      
}

});

Despite setting cookies for both the email and session ID, they are not being stored in the browser's cookie storage after the deployment. I suspect there might be some issue with the way I'm setting the domain and path for the cookies or with the Vercel deployment environment itself.

Any insights or suggestions on how to troubleshoot and resolve this issue would be greatly appreciated. Thank you!


Solution

  • I went ahead and did some debugging and found out that specifying the domain in the res.cookie() method was the cause of my troubles.

    Removing the 'domain' parameter from the res.cookie() method helped.

    If someone has a reason to why specifying the domain hindered cookie storage, I would like to hear it.

    Thank you