node.jsauthenticationsession-cookies

Fetching private API after login with token stored in cookies using authentication middleware


I am trying to create a login system that generates a token and stores it using cookies. I am using authentication middleware. However, when I try to fetch a private API after logging in, it is not working. No errors are being shown.

fetch(`${config.apiUrl}`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      credentials: "include",
      body: JSON.stringify(payload),
});

Solution

  • Common Issues to Check

    1. Cookie Configuration
      res.cookie('token', generatedToken, {
          httpOnly: true,
          secure: process.env.NODE_ENV === 'production', // HTTPS in production
          sameSite: 'strict', // or 'lax' for cross-site
          maxAge: 24 * 60 * 60 * 1000 // 1 day
      });
      

    It means: When in production, set secure: true → the cookie will only be sent over HTTPS. When not in production (like development), secure: false → cookies will be allowed over HTTP (like on localhost).

    1. CORS Configuration

      Your server needs proper CORS settings to allow credentials:

       const corsOptions = {
          origin: 'http://your-frontend-domain.com',
          credentials: true
       };
       app.use(cors(corsOptions));
      
    2. Authentication Middleware

      Ensure your middleware is properly reading the cookie:

      function authenticate(req, res, next) {
         const token = req.cookies.token;
         if (!token) return res.status(401).send('Unauthorized');
      
         try {
           const decoded = jwt.verify(token, process.env.JWT_SECRET);
           req.user = decoded;
           next();
         } catch (err) {
           res.status(401).send('Invalid token');
         }
       }