Cookie Parser: Reading Cookies
Objectives
By the end of this lesson, you should be able to:
- Set a cookie on a response with
res.cookie() - Read cookies sent with a request using
cookie-parser - Explain what the
httpOnlycookie option protects against
💡 Why this matters: Sessions, “remember me” logins, and simple client preferences are frequently stored in cookies, the browser automatically sends them back with every subsequent request to the same site. Reading them cleanly requires this one small piece of middleware.
⚠️ A note on verification: every snippet and every response shown below was actually run and tested with real HTTP requests, using
cookie-parser1.4.
Setting a Cookie
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();
app.use(cookieParser());
app.get('/set-cookie', (req, res) => {
res.cookie('sessionId', 'abc123', { httpOnly: true });
res.send('Cookie set');
});
app.get('/read-cookie', (req, res) => {
res.json({ cookies: req.cookies });
});
app.listen(4209);
curl -i http://localhost:4209/set-cookie | grep -i set-cookie
Set-Cookie: sessionId=abc123; Path=/; HttpOnly
res.cookie(name, value, options) is a response method (available on res without any extra setup) that adds a Set-Cookie header, telling the browser to store this cookie and send it back automatically on future requests to the same site. httpOnly: true prevents the cookie from being read by client-side JavaScript at all (document.cookie won’t see it), only the browser itself sends it back to the server, a meaningful defense against a malicious script (an XSS attack, Module 6) stealing a session cookie.
Reading Cookies Back
curl --cookie "sessionId=abc123" http://localhost:4209/read-cookie
{"cookies":{"sessionId":"abc123"}}
Without cookie-parser, req.headers.cookie would exist as a raw string ("sessionId=abc123; other=value"), needing to be manually split and parsed. app.use(cookieParser()) middleware parses that raw header automatically, making every cookie available as a clean object on req.cookies, req.cookies.sessionId here.
Try It
- Install
cookie-parser, register it, and write a route that sets a cookie withres.cookie(). - Write a second route reading that cookie back via
req.cookies, and test both withcurl, passing the cookie manually with--cookieon the second request. - Set a cookie with
httpOnly: falseinstead, and explain, in your own words, the security difference between that and thehttpOnly: trueversion. - Explain, in your own words, why a session ID cookie should almost always be set with
httpOnly: true.
Recap
res.cookie(name, value, options)sets a cookie via theSet-Cookieresponse header, the browser stores and resends it automatically.cookie-parsermiddleware parses the raw cookie header into a cleanreq.cookiesobject.httpOnly: trueprevents client-side JavaScript from reading a cookie, a meaningful defense against session theft via XSS.
Next lesson: compression, shrinking response sizes automatically.