0
0
NodejsHow-ToBeginner · 4 min read

How to Use Cookies in Node.js: Simple Guide with Examples

In Node.js, you can use the cookie-parser middleware with Express to easily set and read cookies. Use res.cookie() to set a cookie and req.cookies to access cookies sent by the client.
📐

Syntax

To use cookies in Node.js with Express, first install and use the cookie-parser middleware. Then, use res.cookie(name, value, options) to set a cookie and req.cookies to read cookies from the client.

  • res.cookie(name, value, options): Sets a cookie with a name, value, and optional settings like expiration.
  • req.cookies: An object containing cookies sent by the client.
javascript
import express from 'express';
import cookieParser from 'cookie-parser';

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

app.get('/set', (req, res) => {
  res.cookie('token', '123abc', { httpOnly: true, maxAge: 3600000 });
  res.send('Cookie set');
});

app.get('/read', (req, res) => {
  const token = req.cookies.token;
  res.send(`Cookie value: ${token}`);
});
💻

Example

This example shows a simple Express server that sets a cookie named token when visiting /set and reads it back when visiting /read. The cookie is HTTP-only and expires in one hour.

javascript
import express from 'express';
import cookieParser from 'cookie-parser';

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

app.get('/set', (req, res) => {
  res.cookie('token', '123abc', { httpOnly: true, maxAge: 3600000 });
  res.send('Cookie has been set');
});

app.get('/read', (req, res) => {
  const token = req.cookies.token || 'No cookie found';
  res.send(`Cookie value: ${token}`);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 When you visit http://localhost:3000/set, the response is: Cookie has been set When you visit http://localhost:3000/read, the response is: Cookie value: 123abc
⚠️

Common Pitfalls

Common mistakes when using cookies in Node.js include:

  • Not using cookie-parser middleware, so req.cookies is undefined.
  • Forgetting to set httpOnly or secure flags for security.
  • Not setting cookie expiration, causing cookies to be session-only.
  • Trying to read cookies before the middleware runs.

Always ensure middleware order is correct and use secure options in production.

javascript
import express from 'express';
// Missing cookie-parser middleware
const app = express();

app.get('/read', (req, res) => {
  // req.cookies will be undefined here
  res.send(`Cookie value: ${req.cookies?.token || 'No cookie'}`);
});

// Correct way:
import cookieParser from 'cookie-parser';
app.use(cookieParser());
📊

Quick Reference

Method/PropertyDescriptionExample
res.cookie(name, value, options)Sets a cookie in the responseres.cookie('user', 'Alice', { maxAge: 900000 })
req.cookiesReads cookies sent by the clientconst user = req.cookies.user
cookie-parserMiddleware to parse cookiesapp.use(cookieParser())
Options: httpOnlyPrevents client-side JS access{ httpOnly: true }
Options: maxAgeSets cookie expiration in ms{ maxAge: 3600000 }

Key Takeaways

Use the cookie-parser middleware to easily handle cookies in Express.
Set cookies with res.cookie(name, value, options) and read them with req.cookies.
Always set security options like httpOnly and secure for production cookies.
Middleware order matters: cookie-parser must be used before accessing req.cookies.
Set cookie expiration to control how long cookies last on the client.