Express res.clearCookie() Method
What you’ll learn
- How
res.clearCookie()removes cookies in browsers. - Why matching
pathanddomainmatters. - How to clear auth/session cookies during logout flows.
- How to clear multiple cookies safely.
Syntax
javascript
res.clearCookie(name [, options])1
Clear a basic cookie on logout
javascript
app.post('/logout', function (req, res) {
res.clearCookie('token');
res.json({ ok: true });
});2
Clear cookie with matching options
javascript
app.post('/logout-admin', function (req, res) {
res.clearCookie('adminToken', {
path: '/admin',
domain: 'example.com',
sameSite: 'lax',
secure: true
});
res.send('Admin cookie cleared');
});3
Clear multiple cookies
javascript
app.post('/signout', function (req, res) {
res.clearCookie('token');
res.clearCookie('refreshToken');
res.clearCookie('theme');
res.status(204).end();
});⚠️ Common pitfalls
- If
path/domaindo not match the original cookie, clearing may fail silently. - Clear cookies before sending the response body.
- Do not assume server-side cookie removal; the browser clears it after receiving headers.
❓ FAQ
It tells the browser to expire a cookie by sending a Set-Cookie header with an old expiration date.
The cookie options must match the original cookie settings, especially path and domain.
No. res.clearCookie() sends headers directly. cookie-parser is only for reading/parsing request cookies.
Yes, as long as you clear them with matching cookie attributes used during creation.
Yes, call res.clearCookie() once for each cookie name.
Did you know?
To reliably clear a cookie, match the same key options used when setting it, especially path and domain.
4 people found this page helpful
