TExcelTAD
Home › Express & NestJS › Express Mini Project

Express Mini Project

Let's put the course together and build a Bookmarks API: users save links with a title and tags, list them with filtering and pagination, update and delete them — and only ever see their own bookmarks. We'll grow it in four steps, each one a complete, runnable program.

Step Adds
1 app factory, in-memory repository, list + create
2 validation, central errors, read/update/delete
3 authentication with tokens, per-user data
4 filtering by tag, search, pagination

The final layout on disk would look like the one from the Project Structure lesson:

text
bookmarks-api/src/
├── app.js                  createApp({ repo, users })
├── server.js               listen + graceful shutdown
├── lib/http-error.js
├── middleware/authenticate.js
└── features/bookmarks/
    ├── bookmarks.repository.js
    ├── bookmarks.validation.js
    └── bookmarks.routes.js

Step 1: list and create

Start with the smallest thing that works: a repository with async methods and an app factory that receives it.

node · try it yourself
const express = require('express');

function createRepo() {
  const rows = [];
  let nextId = 1;
  return {
    async list() { return rows; },
    async insert(data) { const row = { id: nextId++, ...data }; rows.push(row); return row; },
  };
}

function createApp({ repo }) {
  const app = express();
  app.use(express.json());
  app.get('/bookmarks', async (req, res) => res.json({ data: await repo.list() }));
  app.post('/bookmarks', async (req, res) => {
    const { url, title } = req.body ?? {};
    res.status(201).json({ data: await repo.insert({ url, title }) });
  });
  return app;
}

const server = createApp({ repo: createRepo() }).listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  const post = (body) => fetch(base + '/bookmarks', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });

  let res = await post({ url: 'https://expressjs.com', title: 'Express' });
  console.log(res.status, await res.text());
  res = await fetch(base + '/bookmarks');
  console.log(res.status, await res.text());
  server.close();
});
201 {"data":{"id":1,"url":"https://expressjs.com","title":"Express"}}
200 {"data":[{"id":1,"url":"https://expressjs.com","title":"Express"}]}

It works — but POST {} would happily store { url: undefined }. Time for validation.

Step 2: validation, errors and full CRUD

Add an HttpError class, a validateBookmark function that returns field errors, PATCH/DELETE, and one error handler at the end. URLs are normalised with the WHATWG URL class and only http/https are accepted (a javascript: URL in a bookmark would be an XSS trap for any frontend that renders it):

node · try it yourself
const express = require('express');

class HttpError extends Error {
  constructor(status, message, fields) { super(message); this.status = status; this.fields = fields; }
}

function validateBookmark(body, { partial = false } = {}) {
  const errors = {};
  const out = {};
  if (body.url !== undefined || !partial) {
    let parsed = null;
    try { parsed = new URL(body.url); } catch {}
    if (!parsed || !['http:', 'https:'].includes(parsed.protocol)) errors.url = 'must be an http(s) URL';
    else out.url = parsed.href;
  }
  if (body.title !== undefined || !partial) {
    if (typeof body.title !== 'string' || !body.title.trim() || body.title.length > 100) errors.title = 'must be 1-100 characters';
    else out.title = body.title.trim();
  }
  if (body.tags !== undefined) {
    if (!Array.isArray(body.tags) || !body.tags.every((t) => typeof t === 'string' && /^[a-z0-9-]{1,20}$/.test(t))) {
      errors.tags = 'must be an array of lowercase slugs';
    } else out.tags = [...new Set(body.tags)];
  } else if (!partial) out.tags = [];
  if (Object.keys(errors).length) throw new HttpError(422, 'Validation failed', errors);
  return out;
}

function createRepo() {
  const rows = new Map();
  let nextId = 1;
  return {
    async list() { return [...rows.values()]; },
    async get(id) { return rows.get(id) ?? null; },
    async insert(data) { const row = { id: nextId++, ...data }; rows.set(row.id, row); return row; },
    async update(id, data) { const row = rows.get(id); if (row) Object.assign(row, data); return row ?? null; },
    async remove(id) { return rows.delete(id); },
  };
}

function createApp({ repo }) {
  const app = express();
  app.use(express.json());
  const router = express.Router();

  router.param('id', (req, res, next, raw) => {
    req.id = Number(raw);
    if (!Number.isSafeInteger(req.id) || req.id < 1) throw new HttpError(400, 'invalid id');
    next();
  });
  const findOr404 = async (id) => (await repo.get(id)) ?? Promise.reject(new HttpError(404, 'bookmark not found'));

  router.get('/', async (req, res) => res.json({ data: await repo.list() }));
  router.get('/:id', async (req, res) => res.json({ data: await findOr404(req.id) }));
  router.post('/', async (req, res) => {
    const row = await repo.insert(validateBookmark(req.body ?? {}));
    res.status(201).location(`/bookmarks/${row.id}`).json({ data: row });
  });
  router.patch('/:id', async (req, res) => {
    await findOr404(req.id);
    res.json({ data: await repo.update(req.id, validateBookmark(req.body ?? {}, { partial: true })) });
  });
  router.delete('/:id', async (req, res) => {
    await findOr404(req.id);
    await repo.remove(req.id);
    res.sendStatus(204);
  });

  app.use('/bookmarks', router);
  app.use((req, res) => res.status(404).json({ error: 'route not found' }));
  app.use((err, req, res, next) => {
    const status = err.status ?? 500;
    res.status(status).json({ error: status < 500 ? err.message : 'Internal Server Error', ...(err.fields && { fields: err.fields }) });
  });
  return app;
}

const server = createApp({ repo: createRepo() }).listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  const call = async (method, path, body) => {
    const res = await fetch(base + path, { method, headers: { 'Content-Type': 'application/json' }, body: body && JSON.stringify(body) });
    console.log(`${method} ${path}`.padEnd(20), res.status, await res.text());
  };
  await call('POST', '/bookmarks', { url: 'https://nodejs.org', title: ' Node.js ', tags: ['docs', 'node', 'docs'] });
  await call('POST', '/bookmarks', { url: 'javascript:alert(1)', title: '', tags: ['Bad Tag'] });
  await call('PATCH', '/bookmarks/1', { title: 'Node.js docs' });
  await call('GET', '/bookmarks/1');
  await call('GET', '/bookmarks/abc');
  await call('DELETE', '/bookmarks/1');
  await call('DELETE', '/bookmarks/1');
  server.close();
});
POST /bookmarks      201 {"data":{"id":1,"url":"https://nodejs.org/","title":"Node.js","tags":["docs","node"]}}
POST /bookmarks      422 {"error":"Validation failed","fields":{"url":"must be an http(s) URL","title":"must be 1-100 characters","tags":"must be an array of lowercase slugs"}}
PATCH /bookmarks/1   200 {"data":{"id":1,"url":"https://nodejs.org/","title":"Node.js docs","tags":["docs","node"]}}
GET /bookmarks/1     200 {"data":{"id":1,"url":"https://nodejs.org/","title":"Node.js docs","tags":["docs","node"]}}
GET /bookmarks/abc   400 {"error":"invalid id"}
DELETE /bookmarks/1  204 
DELETE /bookmarks/1  404 {"error":"bookmark not found"}

Notice how short the route handlers are: validation and "not found" are thrown, and the single error handler formats every failure the same way.

Step 3: authentication and per-user data

Each bookmark now belongs to a user. A Bearer token identifies the caller (HMAC-signed, as in the Authentication lesson), and every repository call is scoped by userId — that's what stops Ana from reading Bo's bookmarks, even if she guesses an id:

node · try it yourself
const express = require('express');
const crypto = require('node:crypto');

const SECRET = 'dev-secret';
const sign = (s) => crypto.createHmac('sha256', SECRET).update(s).digest('base64url');
const issueToken = (userId) => `${userId}.${sign(userId)}`;
function verifyToken(token) {
  const [userId, sig] = String(token).split('.');
  if (!userId || !sig) return null;
  const a = Buffer.from(sign(userId)), b = Buffer.from(sig);
  return a.length === b.length && crypto.timingSafeEqual(a, b) ? userId : null;
}

class HttpError extends Error { constructor(status, message) { super(message); this.status = status; } }

function createRepo() {
  const rows = [];
  let nextId = 1;
  return {
    async listFor(userId) { return rows.filter((r) => r.userId === userId); },
    async getFor(userId, id) { return rows.find((r) => r.userId === userId && r.id === id) ?? null; },
    async insert(data) { const row = { id: nextId++, ...data }; rows.push(row); return row; },
  };
}

function authenticate(req, res, next) {
  const [scheme, token] = (req.get('Authorization') ?? '').split(' ');
  req.userId = scheme === 'Bearer' ? verifyToken(token) : null;
  if (!req.userId) throw new HttpError(401, 'authentication required');
  next();
}

function createApp({ repo }) {
  const app = express();
  app.use(express.json());
  const router = express.Router();
  router.use(authenticate);
  router.get('/', async (req, res) => res.json({ data: await repo.listFor(req.userId) }));
  router.get('/:id', async (req, res) => {
    const row = await repo.getFor(req.userId, Number(req.params.id));
    if (!row) throw new HttpError(404, 'bookmark not found'); // also for other users' ids
    res.json({ data: row });
  });
  router.post('/', async (req, res) => {
    const row = await repo.insert({ userId: req.userId, url: req.body.url, title: req.body.title });
    res.status(201).json({ data: row });
  });
  app.use('/bookmarks', router);
  app.use((err, req, res, next) => res.status(err.status ?? 500).json({ error: err.message }));
  return app;
}

const server = createApp({ repo: createRepo() }).listen(0, async () => {
  const base = `http://localhost:${server.address().port}/bookmarks`;
  const as = (user) => ({ 'Content-Type': 'application/json', Authorization: `Bearer ${issueToken(user)}` });
  const show = async (label, res) => console.log(label.padEnd(22), res.status, await res.text());

  await show('ana creates', await fetch(base, { method: 'POST', headers: as('ana'), body: JSON.stringify({ url: 'https://a.dev', title: 'A' }) }));
  await show('bo creates', await fetch(base, { method: 'POST', headers: as('bo'), body: JSON.stringify({ url: 'https://b.dev', title: 'B' }) }));
  await show('ana lists', await fetch(base, { headers: as('ana') }));
  await show("ana reads bo's #2", await fetch(base + '/2', { headers: as('ana') }));
  await show('forged token', await fetch(base, { headers: { Authorization: 'Bearer bo.forged' } }));
  await show('no token', await fetch(base));
  server.close();
});
ana creates            201 {"data":{"id":1,"userId":"ana","url":"https://a.dev","title":"A"}}
bo creates             201 {"data":{"id":2,"userId":"bo","url":"https://b.dev","title":"B"}}
ana lists              200 {"data":[{"id":1,"userId":"ana","url":"https://a.dev","title":"A"}]}
ana reads bo's #2      404 {"error":"bookmark not found"}
forged token           401 {"error":"authentication required"}
no token               401 {"error":"authentication required"}

Note: The token here never expires, to keep the step small. A real API adds an exp claim (see the Authentication lesson) and uses a library such as jose.

Step 4: filter, search and paginate

Finally, the list endpoint grows query options: ?tag= filters by tag, ?q= searches titles, ?sort= orders by title or id (prefix - for descending), and ?page=&limit= paginate with a meta block:

node · try it yourself
const express = require('express');

const seed = [
  { id: 1, title: 'Express guide', tags: ['node', 'web'] },
  { id: 2, title: 'NestJS docs', tags: ['node', 'ts'] },
  { id: 3, title: 'MDN HTTP', tags: ['web'] },
  { id: 4, title: 'TypeScript handbook', tags: ['ts'] },
  { id: 5, title: 'Node streams', tags: ['node'] },
];

function listQuery(query) {
  const int = (v, d) => (Number.isNaN(Number.parseInt(v, 10)) ? d : Number.parseInt(v, 10));
  const sort = typeof query.sort === 'string' ? query.sort : 'id';
  const field = sort.replace(/^-/, '');
  if (!['id', 'title'].includes(field)) {
    throw Object.assign(new Error('sort must be id or title'), { status: 400 });
  }
  return {
    tag: typeof query.tag === 'string' ? query.tag : undefined,
    q: typeof query.q === 'string' ? query.q.toLowerCase() : undefined,
    field,
    dir: sort.startsWith('-') ? -1 : 1,
    page: Math.max(1, int(query.page, 1)),
    limit: Math.min(50, Math.max(1, int(query.limit, 10))),
  };
}

const app = express();
app.get('/bookmarks', (req, res) => {
  const { tag, q, field, dir, page, limit } = listQuery(req.query);
  let rows = seed.filter((b) => (!tag || b.tags.includes(tag)) && (!q || b.title.toLowerCase().includes(q)));
  rows = [...rows].sort((a, b) => (a[field] < b[field] ? -1 : a[field] > b[field] ? 1 : 0) * dir);
  const total = rows.length;
  res.json({
    data: rows.slice((page - 1) * limit, page * limit).map((b) => b.title),
    meta: { page, limit, total, pages: Math.ceil(total / limit) },
  });
});
app.use((err, req, res, next) => res.status(err.status ?? 500).json({ error: err.message }));

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}/bookmarks`;
  for (const qs of ['?tag=node', '?tag=node&sort=-title', '?q=DOC', '?limit=2&page=3', '?sort=url']) {
    const res = await fetch(base + qs);
    console.log(qs.padEnd(22), res.status, await res.text());
  }
  server.close();
});
?tag=node              200 {"data":["Express guide","NestJS docs","Node streams"],"meta":{"page":1,"limit":10,"total":3,"pages":1}}
?tag=node&sort=-title  200 {"data":["Node streams","NestJS docs","Express guide"],"meta":{"page":1,"limit":10,"total":3,"pages":1}}
?q=DOC                 200 {"data":["NestJS docs"],"meta":{"page":1,"limit":10,"total":1,"pages":1}}
?limit=2&page=3        200 {"data":["Node streams"],"meta":{"page":3,"limit":2,"total":5,"pages":3}}
?sort=url              400 {"error":"sort must be id or title"}

Where to go from here

Next feature Lesson to revisit
replace the repository with PostgreSQL or SQLite CRUD API — "From memory to a database"
rate-limit POST /bookmarks Rate Limiting
structured logs with request ids Logging
node --test suite for every endpoint Testing APIs
Dockerfile, health checks, graceful shutdown Deploying Express
rewrite it in NestJS: BookmarksModule, DTOs with class-validator, an AuthGuard the NestJS section

Tip: A great exercise is to port this project to NestJS. Each Express piece has a direct Nest counterpart: the repository becomes a provider, validateBookmark becomes a DTO + ValidationPipe, authenticate becomes a guard, and the error handler becomes an exception filter.

Test yourself

Why does every repository call in step 3 include userId?

  1. For faster lookups
  2. So users can only ever read or change their own bookmarks
  3. Express requires it
  4. To generate ids

Why does the validator reject javascript: URLs?

  1. They are too long
  2. A frontend rendering them as links could execute script (XSS)
  3. new URL can't parse them
  4. They aren't valid JSON

In step 3, what does Ana get when requesting Bo's bookmark by id?

  1. 200 with Bo's bookmark
  2. 403 Forbidden
  3. 404 Not Found
  4. 500