Examples


Express.js - Cookies


What is Cookies?

Cookies are small pieces of data stored in the user's browser, which can be used to maintain user sessions, preferences, and authentication.

Install Dependencies

Express does not handle cookies by default, so install cookie-parser.

npm install express
npm install cookie-parser

Setting Up Cookie in Express.js Server

index.js
const express = require('express');
const cookieParser = require("cookie-parser");

const app = express();
app.use(cookieParser());

const PORT = 5000;

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Storing and Retrieving Cookie Data

You can set cookies using res.cookie().

Setting Cookies

app.get("/set-cookie", (req, res) => {
  res.cookie("username", "Ram", { maxAge: 900000, httpOnly: true });
  res.send("Cookie has been set!");
});
  • maxAge: 900000 - Cookie expires after 900,000ms (15 minutes).
  • httpOnly: true - Cookie is not accessible via JavaScript (helps prevent XSS attacks).

Reading Cookies

Once a cookie is set, you can access it using req.cookies.

app.get("/get-cookie", (req, res) => {
  const username = req.cookies.username;
  res.send(`Username: ${username}`);
});

Deleting Cookies

To remove a cookie, use res.clearCookie().

app.get("/delete-cookie", (req, res) => {
  res.clearCookie("username");
  res.send("Cookie has been deleted.");
});

Run the Server

Run the server using the command is given below.

node index.js
D:\my-app>node index.js
Server is running on http://localhost:5000

Output

The output shows how setting cookies.

Express cookies store name in cookies output

The output shows how reading cookies.

Express cookies get name in cookies output

The output shows how deleting cookies.

Express cookies destroy name in cookies output