Menu
CoddyTech

Remembering with Cookies

Part of the Auth and Security section of Coddy's Node.js journey. Lesson 4 of 17.

HTTP forgets you between requests: each one arrives alone, and the server cannot tell it came from the same browser. A cookie fixes that. The server answers with a Set-Cookie header, and the browser sends the value back in a Cookie header on every later request to that site.

res.cookie(name, value) sets one. Express does not read the Cookie header for you (the cookie-parser package would), so cookies.js gives you parseCookies. Every value arrives as text.

app.get('/theme/:name', (req, res) => {
    res.cookie('theme', req.params.name);
    res.send('Saved');
});

app.get('/', (req, res) => {
    const { theme = 'light' } = parseCookies(req.get('cookie'));
    res.send(`Your theme is ${theme}`);
});
challenge icon

Challenge

Easy
  • GET /visit reads the visits cookie, adds 1, sets the cookie to the new count and answers { "visits": n }.
  • A browser with no cookie gets 1.

Send GET /visit three times, then open Headers to see Set-Cookie.

Try it yourself

import express from 'express';
import { parseCookies } from './cookies.js';
import { notes, users } from './db.js';
import { hashPassword, verifyPassword } from './passwords.js';

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

app.post('/signup', async (req, res) => {
    const username = String(req.body.username ?? '').trim().toLowerCase();
    const password = String(req.body.password ?? '');
    if (!username || password.length < 8) {
        return res.status(400).json({ error: 'Pick a username and a password of at least 8 characters' });
    }
    if (await users.findOne({ username })) {
        return res.status(409).json({ error: 'That username is taken' });
    }
    await users.insertOne({ username, passwordHash: await hashPassword(password) });
    res.status(201).json({ username });
});

app.post('/login', async (req, res) => {
    const username = String(req.body.username ?? '').trim().toLowerCase();
    const user = await users.findOne({ username });
    if (!user || !(await verifyPassword(String(req.body.password ?? ''), user.passwordHash))) {
        return res.status(401).json({ error: 'Wrong username or password' });
    }
    res.json({ username: user.username });
});

// Counts how many times this browser has called GET /visit.
app.get('/visit', (req, res) => {
    const visits = 1;
    res.json({ visits });
});

// Notes. Anyone can read and write them for now.
app.get('/notes', async (req, res) => {
    res.json(await notes.find().toArray());
});

app.post('/notes', async (req, res) => {
    const note = { text: String(req.body.text ?? '') };
    await notes.insertOne(note);
    res.status(201).json(note);
});

app.listen(3000, () => {
    console.log('Vault is running on port 3000');
});
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Auth and Security