Updating Cookie Value
In this apporach, we will modify the existing cookie information that is stored in the user’s browser. By using the res.cookie() method in Express.js, we will set a new value for the cookie
Syntax:
res.cookie('cookieName', 'newCookieValue');
Example: In the below example, firstly we have defined the route /setCookie which sets the cookie value as “Geek“. Then we update the cookie value in the route /updateCookie by using the res.cookie() method. We have updated the cookie value from “Geek” to “w3wiki“.
Javascript
//app.js const express = require( 'express' ); const cookieParser = require( 'cookie-parser' ); const app = express(); // use cookie-parser middleware app.use(cookieParser()); // route to set the initial cookie app.get( '/setCookie' , (req, res) => { res.cookie( 'user' , 'Geek' ); res.send( 'Cookie has been set!' ); }); // route to update the cookie value app.get( '/updateCookie' , (req, res) => { // ensure the 'user' cookie is set before updating const currUserValue = req.cookies.user; if (!currUserValue) { return res.status(400).send( 'Please set the cookie first by visiting /setCookie' ); } // update the cookie value res.cookie( 'user' , 'w3wiki' ); res.send( 'Cookie has been updated!' ); }); app.listen(3000, () => { console.log( 'Server is running on port 3000' ); }); |
Output:
How to manipulate cookies by using ‘Response.cookie()’ in Express?
Cookies are small data that is stored on the client’s computer. Using this cookie various tasks like authentication, session management, etc can be done. In Express JS we can use the cookie-parser middleware to manage the cookies in the application. In this article, we going to manipulate cookies in Express JS by using the two scenarios/approaches below.
Contact Us