Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

You can set cookies in Next.js while using Node.js (Express) as the backend by installing the cookie-parser middleware in the Express server and using the res.cookie() method to set the cookie.

  1. Install the cookie-parser middleware:

    npm install cookie-parser
    
  2. Require the cookie-parser middleware in the Express server:

    const cookieParser = require('cookie-parser');
    const express = require('express');
    const app = express();
    
  3. Use the cookie-parser middleware in the Express server:

    app.use(cookieParser());
    
  4. Set a cookie in the Next.js server by sending a request to the Express server:

    // In the Next.js server
    fetch('/api/set-cookie', {
     method: 'POST',
     body: JSON.stringify({ name: 'myCookie', value: '123' }),
    });
    
    // In the Express server
    app.post('/api/set-cookie', (req, res) => {
     const { name, value } = req.body;
     res.cookie(name, value);
     res.send('Cookie set successfully!');
    });
    
  5. Retrieve the cookie in the Next.js server:

    const cookies = parseCookies(req);
    const myCookie = cookies.myCookie;
    
    function parseCookies(req) {
     const cookie = req.headers.cookie;
     const cookies = {};
     if (cookie) {
       cookie.split(';').forEach((c) => {
         const [key, value] = c.trim().split('=');
         cookies[key] = value;
       });
     }
     return cookies;
    }