Node Express JS Cookies

Node Express js Cookies

Learn Node Express js Cookies

Hi, in this chapter you will learn how to set, get and delete cookies using Node or Express JS.

To handle cookies, we will use the cookie-parser node module.

Run the below command to install cookie-parser node module.

npm install cookie-parser --save

After installing the cookie-parser, import this module on your app and then apply that module as a middleware.

const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();

// APPLYING AS MIDDLEWARE
app.use(cookieParser());

Set Cookie:

res.cookie('cookieName', 'cookieValue', options);

The options argument is an optional object containing additional options, such as cookies expire date, etc. Click here

Get Cookies:

req.cookies.cookieName;

Delete Cookies:

res.clearCookie('cookieName');

Example:

const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();

// APPLYING AS MIDDLEWARE
app.use(cookieParser());

app.get('/', (req, res) => {

    let cookieVal = req.cookies.username;
    let show;
    
    if (cookieVal) {
        show = `Hi ${cookieVal} <br><a href="/delete-cookie">Delete Cookie</a>`;
    } else {
        show = `<a href="/set-cookie">Set Cookie</a><br>
        <a href="/delete-cookie">Delete Cookie</a><br>`;
    }

    res.send(show);
});

// SET COOKIE
app.get('/set-cookie', (req, res) => {
    res.cookie('username', 'Webtutorials.ME', {
        maxAge: 1000 * 60, // 1 min
        httpOnly: true // http only, prevents JavaScript cookie access
    });
    // REDIRECT OT HOME
    res.redirect('/');
});

// DELETE COOKIE
app.get('/delete-cookie', (req, res) => {
    //DELETING username COOKIE
    res.clearCookie('username');
    // REDIRECT OT HOME
    res.redirect('/');

});

app.listen(3000, () => console.log('Your app listening on port 3000'));

Browser Output
Before set cookie express js

After clicking the Set Cookie

Browser Output
after cookie set express js

After clicking the Delete Cookie

Browser Output
After Delete cookie express js

Next isExpress JS Session

Previous is – Express JS Middleware

Leave a Reply

Your email address will not be published. Required fields are marked *