Ask Your Question
1

How can cookies be set in Next.js while using Node.js (Express) as the backend?

asked 2021-05-02 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-12-06 13:00:00 +0000

bukephalos gravatar image

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;
    }
    
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-05-02 11:00:00 +0000

Seen: 10 times

Last updated: Dec 06 '21