Loading

Quipoin Menu

Learn • Practice • Grow

express-js / Express.js Cookies
tutorial

Express.js Cookies

Cookies are small pieces of data stored in the user's browser. They're essential for maintaining state in web applications – remembering logins, user preferences, shopping cart items, and more. Express provides easy methods to work with cookies.

What are Cookies?

Cookies are key-value pairs sent by the server to the browser, which stores them and sends them back with every subsequent request to the same server. They're used for:
  • Session management (login state)
  • Personalization (theme preferences)
  • Tracking (analytics)

Think of cookies as the browser's memory. It remembers small pieces of information about you between visits.

Installing Cookie Parser
npm install cookie-parser
const cookieParser = require('cookie-parser');
app.use(cookieParser());

Setting Cookies

Use `res.cookie()` to set a cookie:
app.get('/set-cookie', (req, res) => {
  <!-- Basic cookie -->
  res.cookie('username', 'john');
 
  <!-- Cookie with options -->
  res.cookie('theme', 'dark', {
    maxAge: 86400000, <!-- 24 hours in milliseconds -->
    httpOnly: true, <!-- Can't be accessed by JavaScript -->
    secure: true, <!-- Only sent over HTTPS -->
    sameSite: 'strict' <!-- CSRF protection -->
  });
 
  res.send('Cookies have been set!');
});

Reading Cookies

After using `cookieParser()`, cookies are available in `req.cookies`:
app.get('/get-cookie', (req, res) => {
  const username = req.cookies.username;
  const theme = req.cookies.theme;
 
  if (!username) {
    return res.send('No username cookie found');
  }
 
  res.send(`Welcome back, ${username}! Your theme is ${theme}.`);
});

Signed Cookies

For security, you can sign cookies to prevent tampering. Pass a secret to `cookieParser()`:
app.use(cookieParser('my-secret-key'));

<!-- Set signed cookie -->
res.cookie('user', { id: 1 }, { signed: true });

<!-- Read signed cookie -->
const user = req.signedCookies.user; <!-- Note: signedCookies, not cookies -->

Deleting Cookies

Use `res.clearCookie()` to remove a cookie:
app.get('/logout', (req, res) => {
  res.clearCookie('username');
  res.clearCookie('theme');
  res.send('Logged out, cookies cleared');
});

Practical Example: Remember Me
app.post('/login', (req, res) => {
  const { username, password, rememberMe } = req.body;
 
  <!-- Validate credentials (simplified) -->
  if (username === 'admin' && password === 'secret') {
    <!-- Set session cookie -->
    if (rememberMe) {
      <!-- 30 days cookie -->
      res.cookie('userId', 1, { maxAge: 30 * 24 * 60 * 60 * 1000, httpOnly: true });
    } else {
      <!-- Session cookie (expires when browser closes) -->
      res.cookie('userId', 1, { httpOnly: true });
    }
   
    res.json({ success: true, message: 'Logged in' });
  } else {
    res.status(401).json({ error: 'Invalid credentials' });
  }
});

<!-- Check login status -->
app.get('/profile', (req, res) => {
  const userId = req.cookies.userId;
 
  if (!userId) {
    return res.status(401).json({ error: 'Not logged in' });
  }
 
  <!-- Fetch user data from database -->
  res.json({ user: { id: userId, name: 'John' } });
});

Two Minute Drill

  • Cookies store small data in the browser and are sent with every request.
  • Use `cookie-parser` middleware to parse cookies into `req.cookies`.
  • Set cookies with `res.cookie(name, value, options)`.
  • Use signed cookies with `signed: true` option for security.
  • Delete cookies with `res.clearCookie(name)`.

Need more clarification?

Drop us an email at career@quipoinfotech.com