Sign-out handling
A user signs out and the server needs to invalidate a session cookie in the browser.
Express.js · Module
Clears a named cookie by sending a Set-Cookie header with an expiration date in the past. Match the original cookie options, but omit expires and maxAge.
Calling this method sends a Set-Cookie response header for the named cookie with an expiration date in the past. Supply cookie options that match the original res.cookie call, except for expires and maxAge, so the browser can identify the cookie to remove.
res.clearCookie(name [, options])| Name | Type | Description |
|---|---|---|
name | String | The name of the cookie to clear. |
options | Object | undefined | Cookie options matching those supplied to res.cookie(), excluding expires and maxAge. |
Response
const express = require('express');
const app = express();
app.get('/logout', (req, res) => {
res.clearCookie('session', { path: '/' });
res.sendStatus(204);
});
app.listen(3000);This route clears the session cookie using the same path used when the cookie was created, then returns a successful empty response.
A user signs out and the server needs to invalidate a session cookie in the browser.
A route removes a cookie scoped to a specific path by repeating that path in the clearing call.
An application retires a client-side preference or feature flag cookie.
It sends a Set-Cookie header whose expiration date is in the past, telling the client that the named cookie has expired. The method returns the response object.
Follow-up: What must match the original cookie? The relevant options, such as path or domain, must be identical, while expires and maxAge should be omitted.
The name argument identifies the cookie. The optional options object contains cookie settings that should match those used by res.cookie, excluding expires and maxAge.
Follow-up: Why does path matter? Cookies with different paths are distinct from the browser's perspective, so clearing one path does not necessarily remove another.
Use res.cookie and res.clearCookie with the same path or other identifying attributes. For example, a cookie created with path '/admin' should be cleared with path '/admin'.
Follow-up: What changed in Express 4.20.0? Passing expires or maxAge to this method was deprecated because those values can prevent reliable clearing.
res.cookie()Set-CookieRFC 6265