res.cookie() sets a cookie on the client by adding a Set-Cookie header to the response.
Syntax
res.cookie(name, value [, options])
Example
const express = require("express");
const app = express();
const PORT = 4800;
app.get("/login", (req, res) => {
res.cookie("sessionId", "abc123", {
maxAge: 3600000,
httpOnly: true,
});
res.send("Logged in, session cookie set");
});
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
Use cases
- Storing session identifiers.
- Remembering user preferences (theme, language).
- Setting short-lived cookies with security options like
httpOnlyandsecure.