devnotes.

res.clearCookie() Function

res.clearCookie() sends a Set-Cookie header that instructs the browser to remove a previously set cookie.

Syntax

res.clearCookie(name [, options])

Example

const express = require("express");
const app = express();
const PORT = 4800;

app.get("/login", (req, res) => {
    res.cookie("sessionId", "abc123");
    res.send("Session cookie set");
});

app.get("/logout", (req, res) => {
    res.clearCookie("sessionId");
    res.send("Session cookie cleared");
});

app.listen(PORT, () => console.log(`Listening on ${PORT}`));

Note: use the same path and domain options that were used when the cookie was originally set, or the browser won't recognize it as the same cookie.

Use cases

  • Clearing session cookies during logout.
  • Removing temporary cookies once they're no longer needed.
  • Resetting stored preferences.
res.clearCookie() Function | DevNotes