0
0
ExpressHow-ToBeginner · 3 min read

How to Get Cookies in Express: Simple Guide with Examples

To get cookies in Express, use the cookie-parser middleware which parses cookies attached to the client request object. After installing and using cookie-parser, access cookies via req.cookies inside your route handlers.
📐

Syntax

First, install and import cookie-parser. Then add it as middleware to your Express app. Inside a route, access cookies with req.cookies.

  • cookieParser(): Middleware to parse cookies.
  • req.cookies: Object containing cookie key-value pairs.
javascript
import express from 'express';
import cookieParser from 'cookie-parser';

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

app.get('/', (req, res) => {
  const cookies = req.cookies;
  res.send(cookies);
});
💻

Example

This example shows a simple Express server that reads cookies sent by the client and sends them back in the response.

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

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

app.get('/', (req, res) => {
  // Access cookies from the request
  const userCookie = req.cookies.user || 'No user cookie found';
  res.send(`User cookie value: ${userCookie}`);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 // When visiting http://localhost:3000 with cookie 'user=Alice', response shows: // User cookie value: Alice // Without cookie, response shows: // User cookie value: No user cookie found
⚠️

Common Pitfalls

Not using cookie-parser middleware: Without it, req.cookies will be undefined.

Forgetting to install cookie-parser: You must install it with npm install cookie-parser.

Trying to read cookies before middleware: Always use app.use(cookieParser()) before your routes.

javascript
import express from 'express';

const app = express();

app.get('/', (req, res) => {
  // This will be undefined because cookie-parser is not used
  console.log(req.cookies);
  res.send('Check console');
});

app.listen(3000);
Output
undefined
📊

Quick Reference

  • Install cookie-parser: npm install cookie-parser
  • Import and use middleware: app.use(cookieParser())
  • Access cookies: req.cookies.cookieName
  • Cookies are key-value pairs sent by the client

Key Takeaways

Use the cookie-parser middleware to access cookies in Express.
Always call app.use(cookieParser()) before your routes.
Access cookies via req.cookies inside route handlers.
Without cookie-parser, req.cookies will be undefined.
Install cookie-parser with npm before using it.