How to Clear Cookie in Express: Simple Guide
In Express, you clear a cookie by using
res.clearCookie('cookieName'). This removes the cookie from the client by setting its expiration date to a past time.Syntax
The basic syntax to clear a cookie in Express is:
res.clearCookie(name, options)
Where:
nameis the name of the cookie to clear.optionsis an optional object to match the cookie's path, domain, or other attributes.
Using the same options as when the cookie was set is important to ensure the cookie is properly cleared.
javascript
res.clearCookie('cookieName', { path: '/' });
Example
This example shows a simple Express server that sets a cookie and then clears it when visiting a different route.
javascript
import express from 'express'; const app = express(); app.get('/set', (req, res) => { res.cookie('user', 'Alice', { path: '/', maxAge: 900000 }); res.send('Cookie has been set'); }); app.get('/clear', (req, res) => { res.clearCookie('user', { path: '/' }); res.send('Cookie has been cleared'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
Common Pitfalls
Common mistakes when clearing cookies include:
- Not specifying the same
pathordomainoptions used when setting the cookie, so the cookie does not get cleared. - Trying to clear a cookie that was never set or misspelling the cookie name.
- Expecting
res.clearCookie()to immediately remove the cookie on the client without a new response.
Always match the cookie options exactly when clearing.
javascript
/* Wrong way: missing path option */ res.clearCookie('user'); /* Right way: include path option if set before */ res.clearCookie('user', { path: '/' });
Quick Reference
Remember these tips when clearing cookies in Express:
- Use
res.clearCookie(name, options)with matching options. - Cookies are cleared by setting expiration to a past date.
- Clearing a cookie sends a Set-Cookie header to the client.
- Check cookie names and paths carefully.
Key Takeaways
Use res.clearCookie('cookieName', options) to clear cookies in Express.
Match the path and domain options used when setting the cookie to clear it properly.
Clearing a cookie sends a response header that tells the browser to remove it.
Always verify the cookie name and options to avoid clearing failures.
res.clearCookie does not delete cookies immediately on the client without a response.