Thuta Learning
Node.js
ExercisesWeb DevelopmentBeginner

Practice: Express Routing, Async/Await & Mini REST API

Node.jsLesson 2845 min

What you'll walk away with

  • Write async route handlers on top of a data store whose methods are async
  • Write a delay() helper that wraps setTimeout in a Promise and use it with await
  • Explain how Express 5 forwards a rejected async handler to the error handler automatically
  • Build a full CRUD flow (GET, POST, PATCH, DELETE) with correct status codes on your own

Explain it simply

Explain it simply

In this practice you build the API for a small bookshop. First you list books, find one book and add a new one; the mini challenge adds editing and deleting.

What is new here is waiting. When you ask a real database something, the answer does not arrive instantly; it takes a few milliseconds. This lesson uses an array as a pretend database, makes every method async and has it wait with delay(). That way, when you connect a real database later, the route code does not need to change.

Problem → Why → Solution

The problem: a forgotten await and Express 4 era advice

The handler below forgets await, so book is a Promise, not an object. A Promise is always truthy, so the 404 check is skipped and res.json(book) sends {}. Nothing throws; the client just receives wrong data.

A second idea you will often read is that an async handler without try/catch crashes the server. That was a real concern in Express 4, which did not catch rejected promises, so a request could hang without ever getting a response. Express 5 changed this.

async-draft.js
app.get('/books/:id', async (req, res) => {
  const book = bookStore.findById(Number(req.params.id)); // missing await
  if (!book) {                                            // a Promise is truthy
    return res.status(404).json({ error: 'Book not found' });
  }
  res.json(book);                                         // sends {}
});

Why it happens

Every async function returns a Promise immediately, and the real value arrives later. await means "pause this function until the value is here". JSON.stringify sees a Promise as an object with no fields, which is why the client receives {}.

Core concept: how async routes behave

Look at the four original tasks one by one and every route follows the same shape: ask the data store with await, then pick a status based on the result.

Tasks 1-3: routes and statuses

GET /books answers 200 with { count, data }; GET /books/:id answers 200 when found and 404 otherwise; POST /books reads the body via express.json(), checks title and author, and answers 201 or 400. The id comes from a nextId counter rather than books.length + 1, so ids never repeat after a delete.

Task 4: the delay() helper

setTimeout uses a callback, so you cannot await it directly. new Promise((resolve) => setTimeout(resolve, ms)) creates a Promise that resolves after ms milliseconds, which lets you write await delay(100). While one request waits, the event loop keeps serving other requests, so the server as a whole never stalls.

Express 5 catches async errors

In Express 5, when a route handler returns a Promise that rejects, Express passes the error to the error handler automatically, as if you had called next(err). You no longer need try/catch in every route, just one error handler at the end of the app. Reach for try/catch only when you want to handle an error on the spot, for example to return a fallback value.

Express 4Express 5
An async handler rejectsNot forwarded; the request may hangForwarded to the error handler
What you must writetry/catch + next(err), or a wrapperNothing extra

Deleting with filter(): who may reassign?

A common way to write DELETE is with array.filter(). filter() returns a new array, so the result has to be stored somewhere. In the mini challenge that reassignment happens only inside the store's remove(), which is safe because the store alone owns the array. Route handlers reassigning a shared array themselves is the kind of bug you met in the GET list lesson.

Mental model: ask, wait, decide
  1. Route calls an async store method
  2. await pauses until the value arrives
  3. Choose 2xx or 4xx from the value
  4. A rejection goes to the error handler

Every call to a store method needs await; without it you are holding a Promise, not a value.

General pattern

javascript
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const store = { async findById(id) { await delay(ms); return found ?? null; } };

app.get('/things/:id', async (req, res) => {
  const thing = await store.findById(Number(req.params.id));
  if (!thing) return res.status(404).json({ error: 'not found' });
  res.json({ data: thing });
});

app.use((err, req, res, next) => res.status(500).json({ error: 'message' }));

Store methods are async and routes await them; any rejected Promise ends up in the single error handler at the bottom.

Books API: four tasks and one async error

bookStore is the pretend database. findById waits 100 ms to simulate Task 4's slow database lookup. The /books/:id/reviews route calls a review service that always fails, showing how Express 5 passes the error along. Timing varies a little between machines, so the output reports whether the request waited roughly 100 ms rather than an exact number.

books-api.js
const express = require('express');

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

// A pretend database: every method is async, just like a real driver
const bookStore = {
  books: [
    { id: 1, title: 'Node.js Basics', author: 'Aung' },
    { id: 2, title: 'Express Guide', author: 'Su' },
  ],
  nextId: 3,
  async findAll() {
    await delay(20);
    return this.books;
  },
  async findById(id) {
    await delay(100); // Task 4: simulate a slow lookup
    return this.books.find((b) => b.id === id) ?? null;
  },
  async create(fields) {
    await delay(20);
    const book = { id: this.nextId++, ...fields };
    this.books.push(book);
    return book;
  },
};

async function fetchReviews() {
  await delay(10);
  throw new Error('Review service is down');
}

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

// Task 1: the whole collection
app.get('/books', async (req, res) => {
  const books = await bookStore.findAll();
  res.json({ count: books.length, data: books });
});

// Task 2 + 4: one book, after an awaited lookup
app.get('/books/:id', async (req, res) => {
  const book = await bookStore.findById(Number(req.params.id));
  if (!book) return res.status(404).json({ error: 'Book not found' });
  res.json({ data: book });
});

// Task 3: create with an auto-increment id
app.post('/books', async (req, res) => {
  const { title, author } = req.body ?? {};
  const ok = (v) => typeof v === 'string' && v.trim() !== '';
  if (!ok(title) || !ok(author)) {
    return res.status(400).json({ error: 'title and author are required' });
  }
  const book = await bookStore.create({ title: title.trim(), author: author.trim() });
  res.status(201).json({ data: book });
});

// A failing dependency: Express 5 sends the rejection to the error handler
app.get('/books/:id/reviews', async (req, res) => {
  res.json({ data: await fetchReviews() });
});

app.use((err, req, res, next) => {
  console.log('  [error handler]', err.message);
  res.status(500).json({ error: 'Something went wrong' });
});

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  async function call(method, path, body) {
    const init = { method, headers: { 'Content-Type': 'application/json' } };
    if (body) init.body = JSON.stringify(body);
    const started = performance.now();
    const res = await fetch(base + path, init);
    const ms = performance.now() - started;
    console.log(`${method} ${path} -> ${res.status}`, JSON.stringify(await res.json()));
    return ms;
  }

  await call('GET', '/books');
  const ms = await call('GET', '/books/2');
  console.log('  waited about 100 ms:', ms >= 90);
  await call('GET', '/books/9');
  await call('POST', '/books', { title: 'Async Patterns', author: 'Hla' });
  await call('POST', '/books', { title: 'No author' });
  await call('GET', '/books/1/reviews');
  server.close();
});

Code breakdown

  1. Promise-based delayconst delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

    When the timer fires it calls resolve, so await delay(100) continues after about 100 ms.

  2. Async store methodreturn this.books.find((b) => b.id === id) ?? null;

    When nothing matches it returns null explicitly instead of undefined, which is also what most database drivers do.

  3. Awaited lookupconst book = await bookStore.findById(Number(req.params.id));

    Thanks to await, book is a book object or null rather than a Promise, so the 404 check works.

  4. Small validatorconst ok = (v) => typeof v === 'string' && v.trim() !== '';

    One check covers both title and author. { title: 'No author' } has no author, so it gets 400.

  5. No try/catch neededres.json({ data: await fetchReviews() });

    When fetchReviews() rejects, Express 5 calls the error handler. In the output the [error handler] line appears just before the client's 500 line.

You should see
GET /books -> 200 {"count":2,"data":[{"id":1,"title":"Node.js Basics","author":"Aung"},{"id":2,"title":"Express Guide","author":"Su"}]}
GET /books/2 -> 200 {"data":{"id":2,"title":"Express Guide","author":"Su"}}
  waited about 100 ms: true
GET /books/9 -> 404 {"error":"Book not found"}
POST /books -> 201 {"data":{"id":3,"title":"Async Patterns","author":"Hla"}}
POST /books -> 400 {"error":"title and author are required"}
  [error handler] Review service is down
GET /books/1/reviews -> 500 {"error":"Something went wrong"}

Waiting for two things at once

Suppose a route needs both a book and its author's profile. Two awaits in a row take about 100 ms + 100 ms = 200 ms. When neither depends on the other, start both with Promise.all([findBook(), findAuthor()]) and await them together; that takes about 100 ms.

Promise.all rejects as soon as one of them rejects, and Express 5 forwards that to the error handler too. If you want to show what succeeded even when one part fails, use Promise.allSettled instead.

In real projects

In real projects

A layer like bookStore, which separates data access from the routes, is usually called a repository or service layer. When you move from PostgreSQL to MongoDB, or want tests to use an in-memory store instead of a real database, you change only this layer and the routes stay the same.

In production the error handler writes the real error, together with a request id, to a logging system (for example as structured JSON logs) and sends the client only a generic message. External dependencies such as a review service fail as a matter of routine, so teams decide on timeouts, retries, or showing the book without reviews when that service is down.

Common mistakes

Common mistakes

Calling a store method without await

A Promise is truthy, so if (!book) is always skipped and the client gets {} with status 200. TypeScript with the typescript-eslint rule no-misused-promises can flag a Promise used in a condition like this.

Awaiting setTimeout directly

await setTimeout(fn, 500) receives a timer object immediately and does not wait at all. Use the Promise-wrapped delay(), or the setTimeout exported by require('node:timers/promises').

Keeping Express 4 wrappers in Express 5

Wrappers such as asyncHandler(fn), or try { } catch (e) { next(e) } in every route, are no longer needed in Express 5. They add code and often end up handling the same error in two places.

Best practices

Best practices

  • Let route handlers touch data only through store methods, never by editing the array directly
  • Write store methods as async from day one, so connecting a database does not change their signatures
  • Keep a single error handler per app, and do the logging and the 500 response there
  • Keep delays short in practice scripts (around 100 ms) so test runs stay fast

Mini challenge

Finish CRUD with PATCH and DELETE

Add update(id, changes) and remove(id) methods to an async store, then write PATCH /books/:id and DELETE /books/:id. PATCH changes only the fields that were sent (title, author); DELETE removes the book with array.filter() and answers 204.

  • PATCH checks every field it receives is a non-empty string and answers 400 otherwise
  • Both PATCH and DELETE answer 404 when the book does not exist
  • remove() returns true when something was removed and false otherwise
  • Calling DELETE twice gives 204 the first time and 404 the second
books-crud.js
const express = require('express');

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const store = {
  books: [/* TODO: three books */],
  async update(id, changes) {
    // TODO: wait, find the book, Object.assign the changes, return it or null
  },
  async remove(id) {
    // TODO: wait, filter the book out, return whether the length shrank
  },
};

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

// TODO: PATCH /books/:id  -> 200 { data } | 400 | 404
// TODO: DELETE /books/:id -> 204 | 404

// TODO: listen on 0, send PATCH x2 and DELETE x2, print results, close

Expected: The first PATCH answers 200 ("Express 5 Guide"), the empty author answers 400, the first DELETE answers 204 (no body) and the second 404, then left: Express 5 Guide | Async Patterns is printed.

Show hint

In PATCH, loop with for (const field of ['title', 'author']) and continue when req.body?.[field] is undefined, so only the fields that were sent get checked.

Show solution
books-crud.js
const express = require('express');

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const store = {
  books: [
    { id: 1, title: 'Node.js Basics', author: 'Aung' },
    { id: 2, title: 'Express Guide', author: 'Su' },
    { id: 3, title: 'Async Patterns', author: 'Hla' },
  ],
  async update(id, changes) {
    await delay(20);
    const book = this.books.find((b) => b.id === id);
    if (!book) return null;
    Object.assign(book, changes);
    return book;
  },
  async remove(id) {
    await delay(20);
    const before = this.books.length;
    this.books = this.books.filter((b) => b.id !== id);
    return this.books.length < before; // true if something was removed
  },
};

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

app.patch('/books/:id', async (req, res) => {
  const changes = {};
  for (const field of ['title', 'author']) {
    const value = req.body?.[field];
    if (value === undefined) continue;
    if (typeof value !== 'string' || value.trim() === '') {
      return res.status(400).json({ error: `${field} must be a non-empty string` });
    }
    changes[field] = value.trim();
  }
  const book = await store.update(Number(req.params.id), changes);
  if (!book) return res.status(404).json({ error: 'Book not found' });
  res.json({ data: book });
});

app.delete('/books/:id', async (req, res) => {
  const removed = await store.remove(Number(req.params.id));
  if (!removed) return res.status(404).json({ error: 'Book not found' });
  res.status(204).end();
});

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  const send = 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, res.status, (await res.text()) || '(no body)');
  };
  await send('PATCH', '/books/2', { title: 'Express 5 Guide' });
  await send('PATCH', '/books/2', { author: '' });
  await send('DELETE', '/books/1');
  await send('DELETE', '/books/1');
  console.log('left:', store.books.map((b) => b.title).join(' | '));
  server.close();
});

Quick quiz 1 / 3

In Express 5, an async route handler awaits a promise that rejects, and there is no try/catch. What happens?

Quick quiz 2 / 3

After const book = bookStore.findById(9); (no await), what does if (!book) do?

Quick quiz 3 / 3

findBook() and findAuthor() each take 100 ms and do not depend on each other. Roughly how long does await Promise.all([findBook(), findAuthor()]) take?

What to remember

  • Keep store methods async and await them in routes, so a real database can replace the array later
  • delay() wraps setTimeout in a Promise, and waiting on it does not block other requests
  • Express 5 forwards rejected async handlers to the error handler, so routes do not need try/catch
  • PATCH validates and changes only the fields sent; DELETE answers 204, or 404 if the book is missing

Express 5 error handling — Express.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Practice: Express Routing, Async/Await & Mini REST API | Thuta Learning