How to Use Cookie Parser in Express: Simple Guide
To use
cookie-parser in Express, first install it with npm install cookie-parser. Then import and add it as middleware using app.use(cookieParser()) to access cookies via req.cookies in your routes.Syntax
The basic syntax to use cookie-parser in Express involves importing the module, then adding it as middleware to your Express app. This middleware parses cookies attached to the client request and makes them available under req.cookies.
const cookieParser = require('cookie-parser'): Imports the cookie-parser module.app.use(cookieParser()): Adds cookie-parser middleware to Express.req.cookies: Object containing parsed cookies.
javascript
const express = require('express'); const cookieParser = require('cookie-parser'); const app = express(); app.use(cookieParser()); app.get('/', (req, res) => { res.send(req.cookies); });
Example
This example shows a simple Express server that uses cookie-parser to read cookies sent by the client. When you visit the root URL, it responds with the cookies as a JSON object.
javascript
const express = require('express'); const cookieParser = require('cookie-parser'); const app = express(); // Use cookie-parser middleware app.use(cookieParser()); // Route to read cookies app.get('/', (req, res) => { res.json({ cookies: req.cookies }); }); // Start server app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
{"cookies":{}}
Common Pitfalls
Common mistakes when using cookie-parser include:
- Not installing the package before using it.
- Forgetting to add
app.use(cookieParser())before routes that need cookies. - Trying to access cookies without parsing them first.
- Confusing
req.cookies(parsed cookies) withreq.headers.cookie(raw cookie string).
Always ensure middleware is added early in the middleware chain.
javascript
/* Wrong way: Missing cookie-parser middleware */ const express = require('express'); const app = express(); app.get('/', (req, res) => { // req.cookies is undefined here res.send(req.cookies); }); app.listen(3000); /* Right way: Add cookie-parser middleware */ const cookieParser = require('cookie-parser'); app.use(cookieParser());
Quick Reference
| Step | Code | Description |
|---|---|---|
| 1 | npm install cookie-parser | Install the cookie-parser package |
| 2 | const cookieParser = require('cookie-parser') | Import cookie-parser in your app |
| 3 | app.use(cookieParser()) | Add cookie-parser middleware |
| 4 | req.cookies | Access parsed cookies in route handlers |
Key Takeaways
Install and import cookie-parser before using it in Express.
Add cookie-parser middleware early with app.use(cookieParser()).
Access cookies easily via req.cookies in your routes.
Do not confuse raw cookie headers with parsed cookies.
Always test that cookies are parsed before using them.