devnotes.

req.cookies Property

req.cookies holds the cookies sent by the client. It's populated by the cookie-parser middleware.

Syntax

req.cookies

Example

const express = require("express");
const cookieParser = require("cookie-parser");
const app = express();
const PORT = 4700;

app.use(cookieParser());

app.get("/set-theme", (req, res) => {
    res.cookie("theme", "dark");
    res.send("Theme cookie set");
});

app.get("/read-theme", (req, res) => {
    res.send(`Current theme: ${req.cookies.theme}`);
});

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

Visiting /set-theme then /read-theme returns Current theme: dark.

Use cases

  • Reading a user's saved preferences.
  • Reading session identifiers.
  • Reading authentication-related cookie values.
req.cookies Property | DevNotes