Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 43 ยท Projects

Project: Authenticated Notes API

Build a Notes API with registration, login, signed tokens, per-user data and authorization checks. Real Express code is read-only; a runnable stand-in proves it works.

Most real APIs need to know who is calling and what they may touch. In this project you build a small Notes API where people register, log in, receive a token, and manage only their own notes. It combines three earlier ideas: middleware that guards routes (Writing Your Own Middleware), token authentication (JWT Authentication) and consistent errors (Error Handling).

The real Express code is read-only on this site. Everything runs on the stand-in framework, which has the same app.get, res.json and (req, res, next) shape, and uses only node:crypto, which is real and available here. One honest difference: real projects use the jsonwebtoken package and argon2 or bcrypt for passwords. Our stand-in signs tokens with HMAC and hashes passwords with Node's built-in scrypt, which is the same idea in fewer moving parts.

The flow

Register Store a salted password hash, never the password.
Login Check the password, return a signed token.
Send token Send it as a Bearer header on each call.
Use notes Every note belongs to one user.
1 / 2

The API contract

Request Needs token Result
POST /api/register no 201, 409 if the email exists, 422 if invalid
POST /api/login no 200 with { token }, or 401
GET /api/notes yes only your notes
POST /api/notes yes 201
GET /api/notes/:id yes 200, or 404
DELETE /api/notes/:id yes 204, or 404

For a note that belongs to someone else, the API answers 404, not 403. A 403 would confirm that the note exists, which tells an attacker which ids are worth guessing. Hiding it is a small, cheap defense.

Passwords and tokens

Passwords are never stored. You store a salted, deliberately slow hash. scrypt from node:crypto is a good built-in choice:

JavaScript
import { randomBytes, scryptSync, timingSafeEqual } from 'node:crypto';

export function hashPassword(password) {
  const salt = randomBytes(16);
  const hash = scryptSync(password, salt, 32);
  return `${salt.toString('hex')}:${hash.toString('hex')}`;
}

export function verifyPassword(password, stored) {
  const [saltHex, hashHex] = stored.split(':');
  const expected = Buffer.from(hashHex, 'hex');
  const actual = scryptSync(password, Buffer.from(saltHex, 'hex'), 32);
  return timingSafeEqual(actual, expected);
}

The random salt makes identical passwords hash differently, and timingSafeEqual compares without leaking how many bytes matched. In production prefer the async scrypt or a package like argon2, so hashing does not block the event loop.

Tokens prove a login happened. A signed token has a payload (user id, expiry) and a signature that only the server can produce. If anyone changes the payload, the signature stops matching:

JavaScript
import { createHmac } from 'node:crypto';

const sign = (data, secret) => createHmac('sha256', secret).update(data).digest('base64url');

export function createToken(payload, secret, ttlMs, now = Date.now()) {
  const body = Buffer.from(JSON.stringify({ ...payload, exp: now + ttlMs })).toString('base64url');
  return `${body}.${sign(body, secret)}`;
}

export function readToken(token, secret, now = Date.now()) {
  const [body, signature] = String(token).split('.');
  if (!body || !signature) return null;
  const expected = sign(body, secret);
  if (signature.length !== expected.length) return null;
  if (!timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) return null;
  const payload = JSON.parse(Buffer.from(body, 'base64url').toString());
  return payload.exp > now ? payload : null;
}

The now parameter has a default but can be passed in. That tiny detail makes expiry testable without waiting. Real JWTs add a header and standard claim names (sub, exp) but follow the same recipe.

The token is signed, not encrypted: anyone can read its payload. Never put secrets in it, and keep the signing secret out of your code, in an environment variable.

The real Express version (read-only)

With real Express and jsonwebtoken, the heart of the project looks like this. It cannot run here, but compare it with the stand-in below: the structure is the same.

JavaScript
import express from 'express';
import jwt from 'jsonwebtoken';
import { hashPassword, verifyPassword } from './passwords.js';

const SECRET = process.env.TOKEN_SECRET;
const users = new Map();   // email -> { id, email, passwordHash }
const notes = new Map();   // id -> { id, userId, text }

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

function authenticate(req, res, next) {
  const header = req.get('authorization') ?? '';
  const token = header.startsWith('Bearer ') ? header.slice(7) : null;
  try {
    req.user = jwt.verify(token, SECRET);   // throws if invalid or expired
    next();
  } catch {
    res.status(401).json({ error: { message: 'Authentication required' } });
  }
}

app.post('/api/login', (req, res) => {
  const user = users.get(req.body?.email);
  if (!user || !verifyPassword(req.body.password, user.passwordHash)) {
    return res.status(401).json({ error: { message: 'Invalid email or password' } });
  }
  const token = jwt.sign({ sub: user.id }, SECRET, { expiresIn: '1h' });
  res.json({ token });
});

app.get('/api/notes', authenticate, (req, res) => {
  res.json([...notes.values()].filter((n) => n.userId === req.user.sub));
});

app.delete('/api/notes/:id', authenticate, (req, res) => {
  const note = notes.get(Number(req.params.id));
  if (!note || note.userId !== req.user.sub) {
    return res.status(404).json({ error: { message: 'Note not found' } });
  }
  notes.delete(note.id);
  res.status(204).end();
});

Two details deserve attention. The login error is the same message for an unknown email and a wrong password, so attackers cannot discover which emails are registered. And every note route filters or checks userId: forgetting that check is the most common authorization bug in real APIs (it is called an insecure direct object reference).

The runnable stand-in

The next example runs the complete flow: register, log in, create notes as two users, and try to read the other person's note. Passwords are really hashed, and tokens are really signed.

Node.js Register, log in and use per-user notes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output as a story. The weak password gets 422, a duplicate email 409, a wrong password 401. Each user lists only their own note, and Bob asking for note 1 gets 404 even though it exists.

Testing the security rules

Security behavior deserves tests, because regressions are silent. The next example attacks the token itself: it changes the payload, truncates the signature and uses an expired token. Because the helpers accept the current time as a parameter, "an hour later" is just a number.

Node.js Tampered and expired tokens are rejected

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Only the first case is accepted. A forged payload keeps the old signature, which no longer matches, and an old token fails the expiry check. That is the entire security of a signed token: the server alone holds the secret.

What to do next

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the API return 404 instead of 403 for another user's note?

    Answering 404 reveals nothing about which ids exist, so guessing ids gives an attacker no information.
  2. 2. Why should login return the same message for an unknown email and a wrong password?

    Distinct messages let an attacker test email addresses against your user base.
  3. 3. What stops someone from editing a token's payload to become another user?

    The payload is only encoded, not secret. The HMAC signature protects it, and a changed payload fails verification.
  4. 4. What is missing if a route reads notes.get(id) and returns it without checking userId?

    Even a logged-in user must only access what belongs to them. Skipping that ownership check is a classic authorization bug.

Summary

  • Store salted slow hashes of passwords; compare with timingSafeEqual.
  • A signed token carries a payload and an expiry; the signature proves the server created it.
  • Authenticate in one middleware (401), authorize each resource access separately (404 or 403).
  • Use identical login errors for unknown email and wrong password.
  • Pass the clock into token helpers so expiry is easy to test.
  • Real projects use jsonwebtoken and argon2 or bcrypt, with the same structure.

Next: Project: Server-Rendered Blog.