Deleting Cookie Value
In this apporach, we will delete the cookie which is already set in the Express.js application. Firstly, we define the route to set the cookie and then we will perform the deletion of the cookie using the res.cookie() method.
Syntax:
res.cookie('cookieName', '', { expires: new Date(0) });
Example: In the below example, we have set the route /setCookie to set the cookie as “Geek“, then we have set another new route as /deleteCookie to delete the cookie which was set. For deleting the cookie, we are passing an empty value wit the immediate expiration in the res.cookie() method.
Javascript
//app.js const express = require( 'express' ); const cookieParser = require( 'cookie-parser' ); // Import cookie-parser const app = express(); // use cookie-parser middleware app.use(cookieParser()); // route to set a cookie app.get( '/setCookie' , (req, res) => { res.cookie( 'user' , 'Geek' ); res.send( 'Cookie has been set!' ); }); // route to delete the cookie app.get( '/deleteCookie' , (req, res) => { // ensure the 'user' cookie is set before deleting const currUserValue = req.cookies.user; if (!currUserValue) { return res.status(400).send( 'Please set the cookie first by visiting /setCookie' ); } // delete the cookie by setting an empty value and an immediate expiration res.cookie( 'user' , '' , { expires: new Date(0) }); res.send( 'Cookie has been deleted!' ); }); a pp.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.