express js clear cookie
To clear a cookie in Express.js, you can follow these steps:
Import the
cookie-parser
middleware: Start by importing thecookie-parser
middleware into your Express application. This middleware will allow you to parse and manipulate cookies in your request and response objects.Use the
cookie-parser
middleware: Next, use thecookie-parser
middleware in your Express application. This can be done by calling thecookieParser()
function and passing it as an argument to theapp.use()
method.Access the cookie value: In the route handler where you want to clear the cookie, you can access the cookie value from the
request.cookies
object. Therequest.cookies
object contains all the cookies sent by the client in the request.Clear the cookie: To clear a cookie, you can use the
response.clearCookie()
method. This method takes the name of the cookie as its argument and clears it from the client's browser.Send the response: Finally, send the response back to the client. This can be done by using the
response.send()
method and passing any desired content or a status message.
Here's an example code snippet that demonstrates how to clear a cookie in Express.js:
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.get('/clear-cookie', (req, res) => {
// Access the cookie value
const cookieValue = req.cookies.cookieName;
// Clear the cookie
res.clearCookie('cookieName');
// Send the response
res.send('Cookie cleared successfully');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Please note that you should replace 'cookieName'
with the actual name of the cookie you want to clear.