Bird
Raised Fist0
Expressframework~5 mins

req.cookies with cookie-parser in Express

Choose your learning style10 modes available
Introduction

We use req.cookies to easily read cookies sent by the browser. The cookie-parser middleware helps Express understand these cookies.

When you want to remember a user's preferences like theme or language.
When you need to check if a user is logged in by reading a session cookie.
When you want to track user visits or behavior with cookies.
When you want to customize content based on stored cookie data.
When you want to read cookies without manually parsing HTTP headers.
Syntax
Express
const cookieParser = require('cookie-parser');
app.use(cookieParser());

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

Call app.use(cookieParser()) before your routes to enable cookie parsing.

req.cookies is an object where each cookie name is a key and its value is the cookie value.

Examples
This logs all cookies sent by the browser as an object.
Express
app.use(cookieParser());

app.get('/', (req, res) => {
  console.log(req.cookies);
  res.send('Check console for cookies');
});
This reads a cookie named username and greets the user by name or as 'Guest' if no cookie.
Express
app.get('/greet', (req, res) => {
  const name = req.cookies.username || 'Guest';
  res.send(`Hello, ${name}!`);
});
This checks a cookie loggedIn to decide what message to show.
Express
app.get('/check', (req, res) => {
  if (req.cookies.loggedIn === 'true') {
    res.send('Welcome back!');
  } else {
    res.send('Please log in.');
  }
});
Sample Program

This Express app sets a cookie named username with value 'Alice' at /setcookie. Then at /showcookie, it reads and shows the cookie value using req.cookies.

Express
const express = require('express');
const cookieParser = require('cookie-parser');

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

app.get('/setcookie', (req, res) => {
  res.cookie('username', 'Alice');
  res.send('Cookie has been set');
});

app.get('/showcookie', (req, res) => {
  const user = req.cookies.username || 'No cookie found';
  res.send(`Username cookie value: ${user}`);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Cookies are sent by the browser with each request, so req.cookies is available only after cookie-parser middleware runs.

Cookies are strings. If you store JSON, you need to parse it yourself.

For security, avoid storing sensitive info directly in cookies.

Summary

req.cookies holds cookies sent by the browser as an object.

cookie-parser middleware must be used to fill req.cookies.

Use cookies to remember user info or preferences easily.

Practice

(1/5)
1. What does req.cookies represent in an Express app when using cookie-parser middleware?
easy
A. A function to set cookies on the response
B. An object containing cookies sent by the browser
C. A string of all cookies concatenated
D. An array of cookie names only

Solution

  1. Step 1: Understand the role of cookie-parser

    The cookie-parser middleware parses cookies from the HTTP request headers.
  2. Step 2: Identify what req.cookies holds

    After parsing, req.cookies is an object where each cookie name is a key and its value is the cookie's value.
  3. Final Answer:

    An object containing cookies sent by the browser -> Option B
  4. Quick Check:

    req.cookies = object of cookies [OK]
Hint: Remember: req.cookies is an object, not a string or function [OK]
Common Mistakes:
  • Thinking req.cookies is a function
  • Expecting req.cookies to be a string
  • Confusing req.cookies with response cookies
2. Which of the following is the correct way to use cookie-parser middleware in an Express app?
easy
A. app.use(cookieParser);
B. app.cookieParser();
C. app.use(cookieParser());
D. ;)(resraPeikooc.ppa

Solution

  1. Step 1: Recall middleware usage in Express

    Middleware functions are added using app.use() and must be called as functions if they return middleware.
  2. Step 2: Apply this to cookie-parser

    The correct syntax is app.use(cookieParser()); to invoke the function and add the middleware.
  3. Final Answer:

    app.use(cookieParser()); -> Option C
  4. Quick Check:

    Middleware added with app.use(cookieParser()) [OK]
Hint: Use parentheses to call middleware function inside app.use [OK]
Common Mistakes:
  • Forgetting parentheses after cookieParser
  • Calling cookieParser as a method on app
  • Passing cookieParser without calling it
3. Given this Express route with cookie-parser middleware, what will be the output if the browser sends a cookie named user with value alice?
app.get('/profile', (req, res) => {
  res.send(`User: ${req.cookies.user}`);
});
medium
A. User: [object Object]
B. User: undefined
C. Error: req.cookies is not defined
D. User: alice

Solution

  1. Step 1: Check if cookie-parser is used

    Assuming cookie-parser middleware is active, req.cookies contains parsed cookies.
  2. Step 2: Access the user cookie value

    The code accesses req.cookies.user, which equals 'alice' from the browser cookie.
  3. Final Answer:

    User: alice -> Option D
  4. Quick Check:

    Cookie value accessed correctly = User: alice [OK]
Hint: Access cookie by name on req.cookies object [OK]
Common Mistakes:
  • Not using cookie-parser so req.cookies is undefined
  • Trying to access cookies as a string
  • Assuming cookie names are case-insensitive
4. What is wrong with this Express code snippet if req.cookies is always undefined?
const express = require('express');
const cookieParser = require('cookie-parser');
const app = express();

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

app.use(cookieParser());
medium
A. cookie-parser middleware is added after the route, so req.cookies is undefined
B. cookie-parser is not imported correctly
C. The route handler should use res.cookies instead
D. Express does not support cookies natively

Solution

  1. Step 1: Check middleware order

    Middleware must be added before routes to affect req objects in those routes.
  2. Step 2: Identify the problem in code

    Here, app.use(cookieParser()) is after the route, so req.cookies is not set when the route runs.
  3. Final Answer:

    cookie-parser middleware is added after the route, so req.cookies is undefined -> Option A
  4. Quick Check:

    Middleware order matters = cookie-parser middleware is added after the route, so req.cookies is undefined [OK]
Hint: Add middleware before routes to access req.cookies [OK]
Common Mistakes:
  • Placing middleware after routes
  • Confusing req.cookies with res.cookies
  • Not calling cookieParser as a function
5. You want to create an Express route that reads a cookie named theme and sends back 'Dark mode' if its value is 'dark', otherwise 'Light mode'. Which code correctly implements this using req.cookies with cookie-parser?
hard
A. app.get('/mode', (req, res) => { if (req.cookies.theme === 'dark') res.send('Dark mode'); else res.send('Light mode'); });
B. app.get('/mode', (req, res) => { if (req.cookies['theme'] = 'dark') res.send('Dark mode'); else res.send('Light mode'); });
C. app.get('/mode', (req, res) => { if (req.cookies.theme == dark) res.send('Dark mode'); else res.send('Light mode'); });
D. app.get('/mode', (req, res) => { if (req.cookies.theme === dark) res.send('Dark mode'); else res.send('Light mode'); });

Solution

  1. Step 1: Check cookie access and comparison

    Use strict equality === to compare req.cookies.theme to the string 'dark'.
  2. Step 2: Identify correct syntax

    app.get('/mode', (req, res) => { if (req.cookies.theme === 'dark') res.send('Dark mode'); else res.send('Light mode'); }); uses === and string 'dark' correctly. app.get('/mode', (req, res) => { if (req.cookies['theme'] = 'dark') res.send('Dark mode'); else res.send('Light mode'); }); uses assignment = instead of comparison. app.get('/mode', (req, res) => { if (req.cookies.theme == dark) res.send('Dark mode'); else res.send('Light mode'); }); uses loose equality == with unquoted dark. app.get('/mode', (req, res) => { if (req.cookies.theme === dark) res.send('Dark mode'); else res.send('Light mode'); }); uses undefined variable dark without quotes.
  3. Final Answer:

    The code using strict equality req.cookies.theme === 'dark' -> Option A
  4. Quick Check:

    Use === 'dark' to compare cookie value [OK]
Hint: Use === and quotes for string comparison with cookie values [OK]
Common Mistakes:
  • Using = instead of === for comparison
  • Not quoting string literals
  • Using loose equality == instead of ===
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard