Skip to main content

Web frameworks · Intermediate · 26 min

Structure an Express 5 app with routers, middleware and error handling

By Padding · Updated 18 Nov 2026
Express 5.3.0 · Zod 4.6 · supertest 7.3 · Node.js 26.13 (node:26 image)

You will build a small projects-and-tasks API in Express 5.3 split into routers and modules, with request ids, JSON logs, Zod validation, one central error handler, configuration from environment variables and route tests with supertest.

On this page

A one-file Express API is fine for five routes. By twenty, the same file holds validation, logging, configuration, error replies and every route at once, and a change to one of them means scrolling past the rest. This tutorial builds a small API with the structure that keeps growth cheap: one module per job, routers per resource, and a single place where every error turns into a response.

The API tracks projects and their tasks. You will write it as a set of small files:

Text
src/
  server.js              starts listening; the only file that reads process.env
  config.js              checks environment variables with Zod
  app.js                 builds the Express app from its parts
  lib/http-error.js      an Error that carries an HTTP status
  lib/logger.js          one JSON line per log entry
  middleware/            request id, request logging, validation, 404 and errors
  projects/              store, schemas and the two routers for this resource
test/projects.test.js    route tests with supertest and node:test

The point of each split is that it can be replaced or tested alone. Data lives in memory behind a store object, so a real database later changes one file. If you have not built an Express 5 API before, start with build a REST API with Express 5, which covers status codes and body parsing in one file.

Step 1 · Create the project and the folders

Make a throwaway project folder, turn on ES modules, and install the three packages. The ~ ranges allow patch releases only, so a new minor version cannot change behaviour under you:

Bash
mkdir -p ~/express-structure-demo
cd ~/express-structure-demo
npm init -y
npm pkg set type=module
npm install express@~5.3.0 zod@~4.6.7
npm install --save-dev supertest@~7.3.2
mkdir -p src/lib src/middleware src/projects test

Express is the framework, Zod checks the shape of data at runtime, and supertest sends requests to an app in tests without you starting a server on a fixed port.

Check it worked

Bash
npm ls --depth=0

The list shows express@5.3.0, supertest@7.3.2 and zod@4.6.7, or later patch releases of each.

Step 2 · Read configuration from environment variables

Settings that change between your laptop and a server, such as the port, the address to listen on and how much to log, come from environment variables. Read them in one place and check them as soon as the process starts. A typo in a port number should stop the server with a clear message, not surface later as a strange failure.

Create src/config.js:

Bash
cat > src/config.js <<'JS'
import * as z from 'zod'

const Env = z.object({
  PORT: z.coerce.number().int().min(1).max(65535).default(3000),
  HOST: z.string().min(1).default('127.0.0.1'),
  LOG_LEVEL: z.enum(['info', 'error', 'silent']).default('info'),
})

export function loadConfig(env) {
  const result = Env.safeParse(env)
  if (!result.success) {
    throw new Error(`Invalid configuration:\n${z.prettifyError(result.error)}`)
  }
  const { PORT, HOST, LOG_LEVEL } = result.data
  return { port: PORT, host: HOST, logLevel: LOG_LEVEL }
}
JS

Environment variables are always strings, so z.coerce.number() converts PORT before checking that it is a whole number in the valid range. Each variable has a default, so the app runs with no setup at all. loadConfig takes the environment as an argument instead of reading process.env itself, which makes it easy to call with test values.

Now a logger that writes one JSON object per line. Log tools on servers can search and filter JSON lines by field, which plain sentences do not allow. Create src/lib/logger.js:

Bash
cat > src/lib/logger.js <<'JS'
const RANK = { info: 1, error: 2, silent: 3 }

export function createLogger(level = 'info') {
  const write = (entryLevel, fields) => {
    if (RANK[entryLevel] < RANK[level]) return
    const line = JSON.stringify({ time: new Date().toISOString(), level: entryLevel, ...fields })
    const stream = entryLevel === 'error' ? process.stderr : process.stdout
    stream.write(line + '\n')
  }
  return {
    info: (fields) => write('info', fields),
    error: (fields) => write('error', fields),
  }
}
JS

With LOG_LEVEL=error only errors are written, and silent writes nothing. When the app outgrows this, a library such as pino has the same info and error shape, so the rest of the code does not change.

Check it worked

Call loadConfig with one good and one bad value:

Bash
node --input-type=module -e "import { loadConfig } from './src/config.js'; console.log(loadConfig({ PORT: '4000' }))"
node --input-type=module -e "import { loadConfig } from './src/config.js'; try { loadConfig({ PORT: 'eighty' }) } catch (e) { console.log(e.message) }"

The first prints { port: 4000, host: '127.0.0.1', logLevel: 'info' }, with the two defaults filled in. The second prints Invalid configuration: followed by Zod's summary, something like Invalid input: expected number, received NaN and at PORT.

Step 3 · Add request ids and request logging

Every request gets an id. It goes into the X-Request-Id response header, into every log line for that request and, later, into every error body. When someone reports "it failed at 14:02", the id in their error message leads you straight to the matching log lines. That matters most for users you cannot sit next to: a customer on a patchy mobile connection who retried three times can send you the id from the last attempt.

Create src/middleware/request-id.js:

Bash
cat > src/middleware/request-id.js <<'JS'
import { randomUUID } from 'node:crypto'

const SAFE_ID = /^[A-Za-z0-9._-]{1,64}$/

export function requestId(req, res, next) {
  const incoming = req.get('x-request-id')
  req.id = incoming && SAFE_ID.test(incoming) ? incoming : randomUUID()
  res.set('X-Request-Id', req.id)
  next()
}
JS

If a reverse proxy in front of the app already set an id, the app keeps it, so both sets of logs share one id. An incoming id must be short and use only safe characters, otherwise a caller could write line breaks or huge strings into your logs; anything else is replaced by a fresh UUID.

Now the request logger. Create src/middleware/request-logger.js:

Bash
cat > src/middleware/request-logger.js <<'JS'
export function requestLogger(log) {
  return (req, res, next) => {
    const started = performance.now()
    const { method, path } = req
    res.on('finish', () => {
      log.info({
        msg: 'request',
        requestId: req.id,
        method,
        path,
        status: res.statusCode,
        ms: Math.round(performance.now() - started),
      })
    })
    next()
  }
}
JS

Two details. The logger writes its line on the response's finish event, after the status code is final, so it records what the caller actually received, errors included. It saves req.path at the start, because routers change req.url while they work, and path leaves out the query string, where people sometimes put tokens that should not reach logs.

requestLogger is a function that returns the middleware. That pattern, a factory taking its dependencies as arguments, repeats through the app: nothing imports a global logger, so a test can hand in a fake one.

Check it worked

Bash
ls src/middleware

The output lists request-id.js and request-logger.js.

Step 4 · Send every error to one handler

Handlers should not each decide how an error looks. They throw, and one error middleware at the end of the app turns whatever arrived into a response. Start with an error class that carries a status. Create src/lib/http-error.js:

Bash
cat > src/lib/http-error.js <<'JS'
export class HttpError extends Error {
  constructor(status, message, details) {
    super(message)
    this.name = 'HttpError'
    this.status = status
    this.details = details
  }
}
JS

Then the last two middleware of the app. Create src/middleware/errors.js:

Bash
cat > src/middleware/errors.js <<'JS'
import { HttpError } from '../lib/http-error.js'

export function notFound(req, res, next) {
  next(new HttpError(404, `No route for ${req.method} ${req.path}`))
}

export function errorHandler(log) {
  return (err, req, res, next) => {
    if (res.headersSent) return next(err)

    let status = 500
    let body = { error: 'Internal server error' }
    if (err instanceof HttpError) {
      status = err.status
      body = { error: err.message, details: err.details }
    } else if (err?.type === 'entity.parse.failed') {
      status = 400
      body = { error: 'Body is not valid JSON' }
    } else if (err?.type === 'entity.too.large') {
      status = 413
      body = { error: 'Body is too large' }
    } else {
      log.error({ msg: 'unhandled error', requestId: req.id, stack: err?.stack ?? String(err) })
    }
    res.status(status).json({ ...body, requestId: req.id })
  }
}
JS

How this works:

  • notFound runs only when no route matched, because it is registered after all of them. It does not reply itself. It passes an HttpError to next, so 404s get the same shape as every other error.
  • Express treats a middleware with four parameters as an error handler. Keep all four, even when next looks unused.
  • Errors you created on purpose (HttpError) and the JSON parser's two known errors become clear replies. Anything else is a bug: the caller gets a fixed message and the request id, and the stack trace goes to your log, never into the response.
  • If headers were already sent, a reply is impossible, so the handler passes the error to Express's own handler, which closes the connection.

details is left out of the JSON when it is undefined, because JSON.stringify drops such keys. To give these bodies a standard format that clients can rely on, see return consistent API errors with Problem Details; the change is limited to this one file.

Check it worked

Bash
node --input-type=module -e "import { notFound, errorHandler } from './src/middleware/errors.js'; console.log(notFound.length, errorHandler(console).length)"

The output is 3 4: notFound is ordinary middleware with three parameters, and the handler has the four that mark it as an error handler.

Step 5 · Validate request bodies with Zod

Validation is another job with its own module. A schema describes a valid body, and one middleware applies any schema to req.body. Create src/projects/schemas.js:

Bash
cat > src/projects/schemas.js <<'JS'
import * as z from 'zod'

const name = z.string().trim().min(1).max(80)
const title = z.string().trim().min(1).max(120)

export const NewProject = z.strictObject({ name })

export const NewTask = z.strictObject({
  title,
  done: z.boolean().default(false),
})

export const TaskChanges = z
  .strictObject({ title, done: z.boolean() })
  .partial()
  .refine((changes) => Object.keys(changes).length > 0, {
    error: 'Send title, done or both',
  })
JS

z.strictObject rejects keys the schema does not list, so a typo such as titel is an error instead of being silently ignored. .trim() runs before the length checks, so a name of only spaces fails. TaskChanges makes both fields optional with .partial(), then refuses an empty object.

Now the middleware. Create src/middleware/validate.js:

Bash
cat > src/middleware/validate.js <<'JS'
import { HttpError } from '../lib/http-error.js'

export function validate(schema) {
  return (req, res, next) => {
    const result = schema.safeParse(req.body)
    if (!result.success) {
      const details = result.error.issues.map((issue) => ({
        field: issue.path.join('.') || 'body',
        message: issue.message,
      }))
      throw new HttpError(422, 'Request body is not valid', details)
    }
    req.body = result.data
    next()
  }
}
JS

safeParse returns either the cleaned data or a list of issues, and never throws. On failure the middleware throws an HttpError with every issue listed, and the error handler from the previous step formats it. On success it replaces req.body with Zod's output: trimmed strings, the default for done, and nothing extra. Route handlers after it can trust the body completely.

In Express 5, req.body is undefined when the request had no JSON content type. Zod then reports one issue with an empty path, which the middleware labels body.

Check it worked

Bash
node --input-type=module -e "import { NewTask } from './src/projects/schemas.js'; console.log(NewTask.parse({ title: '  Plan launch  ' })); console.log(NewTask.safeParse({ titel: 'x' }).error.issues.length)"

The first line is { title: 'Plan launch', done: false }: trimmed, with the default added. The second is 2, one issue for the missing title and one for the unknown key.

Step 6 · Write the store and the routers

The store holds the data. Its functions are async, like a database driver's, so swapping in a real database later changes this file and nothing else. Create src/projects/store.js:

Bash
cat > src/projects/store.js <<'JS'
export function createStore() {
  const projects = new Map()
  const tasks = new Map()
  let nextProjectId = 1
  let nextTaskId = 1

  return {
    async listProjects() {
      return [...projects.values()]
    },
    async getProject(id) {
      return projects.get(id)
    },
    async createProject({ name }) {
      const project = { id: nextProjectId++, name }
      projects.set(project.id, project)
      return project
    },
    async listTasks(projectId) {
      return [...tasks.values()].filter((task) => task.projectId === projectId)
    },
    async addTask(projectId, { title, done }) {
      const task = { id: nextTaskId++, projectId, title, done }
      tasks.set(task.id, task)
      return task
    },
    async updateTask(projectId, taskId, changes) {
      const task = tasks.get(taskId)
      if (!task || task.projectId !== projectId) return undefined
      const updated = { ...task, ...changes }
      tasks.set(taskId, updated)
      return updated
    },
  }
}
JS

The store knows nothing about HTTP. It returns undefined for a missing record, and the routers decide that means 404.

Each router is a mini app for one part of the URL space. Create src/projects/projects-router.js:

Bash
cat > src/projects/projects-router.js <<'JS'
import { Router } from 'express'
import { HttpError } from '../lib/http-error.js'
import { validate } from '../middleware/validate.js'
import { NewProject } from './schemas.js'
import { tasksRouter } from './tasks-router.js'

export function projectsRouter(store) {
  const router = Router()

  async function loadProject(req, res, next) {
    const project = await store.getProject(Number(req.params.projectId))
    if (!project) throw new HttpError(404, 'Project not found')
    res.locals.project = project
    next()
  }

  router.get('/', async (req, res) => {
    res.json(await store.listProjects())
  })

  router.post('/', validate(NewProject), async (req, res) => {
    const project = await store.createProject(req.body)
    res.status(201).location(`${req.baseUrl}/${project.id}`).json(project)
  })

  router.get('/:projectId', loadProject, (req, res) => {
    res.json(res.locals.project)
  })

  router.use('/:projectId/tasks', loadProject, tasksRouter(store))

  return router
}
JS

There is no try or catch anywhere. When loadProject throws, its async function returns a rejected promise, and Express 5 passes the rejection to the error handler. Express 4 ignored the returned promise, so a forgotten catch became an unhandled rejection, which stops the whole Node.js process (on very old Node versions the request just hung). The same holds when the store's promise rejects inside a handler.

loadProject runs before the single-project route and before the whole tasks router, so the lookup and its 404 live in one place. It stores the project in res.locals, which lasts for one request. A child router does not see its parent's :projectId unless it is created with Router({ mergeParams: true }); loading the project in the parent avoids needing that. A text id such as abc becomes NaN, which matches no project, so it gets the same 404.

Create src/projects/tasks-router.js:

Bash
cat > src/projects/tasks-router.js <<'JS'
import { Router } from 'express'
import { HttpError } from '../lib/http-error.js'
import { validate } from '../middleware/validate.js'
import { NewTask, TaskChanges } from './schemas.js'

export function tasksRouter(store) {
  const router = Router()

  router.get('/', async (req, res) => {
    res.json(await store.listTasks(res.locals.project.id))
  })

  router.post('/', validate(NewTask), async (req, res) => {
    const task = await store.addTask(res.locals.project.id, req.body)
    res.status(201).json(task)
  })

  router.patch('/:taskId', validate(TaskChanges), async (req, res) => {
    const task = await store.updateTask(res.locals.project.id, Number(req.params.taskId), req.body)
    if (!task) throw new HttpError(404, 'Task not found')
    res.json(task)
  })

  return router
}
JS

The tasks router's paths are relative: / here is /api/projects/1/tasks once mounted. It never repeats the prefix, so moving the resource to a new URL is a one-line change where it is mounted.

Check it worked

Bash
find src -name '*.js' | sort

The output lists eleven files: config.js, the two in lib, the four in middleware and the four in projects. app.js and server.js come next.

Step 7 · Assemble the app and run it

app.js puts the pieces in order. Order is the whole design: middleware runs top to bottom, so the request id comes first (every later line can use it), the routes sit in the middle, and the 404 and error handlers come last. Create src/app.js:

Bash
cat > src/app.js <<'JS'
import express from 'express'
import { errorHandler, notFound } from './middleware/errors.js'
import { requestId } from './middleware/request-id.js'
import { requestLogger } from './middleware/request-logger.js'
import { projectsRouter } from './projects/projects-router.js'

export function createApp({ log, store }) {
  const app = express()
  app.disable('x-powered-by')

  app.use(requestId)
  app.use(requestLogger(log))
  app.use(express.json({ limit: '10kb' }))

  app.get('/api/health', (req, res) => {
    res.json({ status: 'ok' })
  })
  app.use('/api/projects', projectsRouter(store))

  app.use(notFound)
  app.use(errorHandler(log))
  return app
}
JS

createApp receives its logger and store instead of creating them. Only server.js reads the environment and wires real objects together. Create it:

Bash
cat > src/server.js <<'JS'
import { createApp } from './app.js'
import { loadConfig } from './config.js'
import { createLogger } from './lib/logger.js'
import { createStore } from './projects/store.js'

let config
try {
  config = loadConfig(process.env)
} catch (error) {
  console.error(error.message)
  process.exit(1)
}

const log = createLogger(config.logLevel)
const app = createApp({ log, store: createStore() })

const server = app.listen(config.port, config.host, (error) => {
  if (error) throw error
  log.info({ msg: 'listening', url: `http://${config.host}:${config.port}` })
})

for (const signal of ['SIGINT', 'SIGTERM']) {
  process.on(signal, () => server.close(() => process.exit(0)))
}
JS

Add a .env file for local settings, keep it out of version control, and add scripts. --env-file-if-exists makes Node load .env when it exists and carry on without it, and a variable already set in the shell wins over the file. Later secrets, such as a database password, go in .env locally and in the service's environment on a server, never in code:

Bash
cat > .env <<'ENV'
PORT=3000
LOG_LEVEL=info
ENV
printf 'node_modules\n.env\n' > .gitignore
npm pkg set scripts.start="node --env-file-if-exists=.env src/server.js"
npm pkg set scripts.dev="node --watch --env-file-if-exists=.env src/server.js"

Start it in a second terminal. npm run dev restarts the server when you save a file:

Bash
cd ~/express-structure-demo
npm run dev

The server prints one JSON line with "msg":"listening" and the address. In your first terminal, create a project, add a task and finish it:

Bash
curl -s -w '\n' --json '{"name": "Website relaunch"}' http://127.0.0.1:3000/api/projects
curl -s -w '\n' --json '{"title": "  Write the About page "}' http://127.0.0.1:3000/api/projects/1/tasks
curl -s -w '\n' -X PATCH --json '{"done": true}' http://127.0.0.1:3000/api/projects/1/tasks/1
curl -s -w '\n' http://127.0.0.1:3000/api/projects/1/tasks

The replies are {"id":1,"name":"Website relaunch"}, then the task with its title trimmed and "done":false, then the same task with "done":true, then a list holding that one task.

Now send requests that go wrong in different ways:

Bash
curl -s -w '\n%{http_code}\n' --json '{"title": "", "colour": "red"}' http://127.0.0.1:3000/api/projects/1/tasks
curl -s -w '\n%{http_code}\n' http://127.0.0.1:3000/api/projects/9/tasks
curl -s -w '\n%{http_code}\n' -X PATCH --json '{}' http://127.0.0.1:3000/api/projects/1/tasks/1
curl -s -w '\n%{http_code}\n' --json '{oops' http://127.0.0.1:3000/api/projects
curl -s -w '\n%{http_code}\n' http://127.0.0.1:3000/api/teams

Every reply is JSON with an error and a requestId. The first is 422 with two details, one for title and one for the unknown key colour. Then come 404 with Project not found, 422 with Send title, done or both, 400 with Body is not valid JSON and 404 with No route for GET /api/teams.

Check it worked

Send your own request id and look at the response headers:

Bash
curl -si -H 'X-Request-Id: support-ticket-118' http://127.0.0.1:3000/api/projects/9

The headers include X-Request-Id: support-ticket-118, and the body ends with "requestId":"support-ticket-118". In the server terminal, the matching log line reads something like {"time":"...","level":"info","msg":"request","requestId":"support-ticket-118","method":"GET","path":"/api/projects/9","status":404,"ms":1}.

Stop the server with Ctrl+C, then try a broken setting. The shell's value wins over .env:

Bash
PORT=eighty npm start

It prints Invalid configuration: with the problem at PORT, and exits without listening.

Step 8 · Test the routes with supertest

Because createApp takes its logger and store as arguments, each test builds a fresh app with an empty store and a fake logger. supertest takes the app itself, listens on a free port for the length of one request, and gives you the response. Node's own test runner does the rest. Create test/projects.test.js:

Bash
cat > test/projects.test.js <<'JS'
import assert from 'node:assert/strict'
import { test } from 'node:test'
import request from 'supertest'
import { createApp } from '../src/app.js'
import { createStore } from '../src/projects/store.js'

function setup(store = createStore()) {
  const errors = []
  const log = { info() {}, error: (entry) => errors.push(entry) }
  return { app: createApp({ log, store }), errors }
}

test('creates a project, adds a task and completes it', async () => {
  const { app } = setup()
  const created = await request(app).post('/api/projects').send({ name: 'Website' }).expect(201)
  assert.equal(created.headers.location, '/api/projects/1')

  await request(app).post('/api/projects/1/tasks').send({ title: ' Draft copy ' }).expect(201)
  await request(app).patch('/api/projects/1/tasks/1').send({ done: true }).expect(200)

  const list = await request(app).get('/api/projects/1/tasks').expect(200)
  assert.deepEqual(list.body, [{ id: 1, projectId: 1, title: 'Draft copy', done: true }])
})

test('every response carries a request id', async () => {
  const { app } = setup()
  const fresh = await request(app).get('/api/health').expect(200)
  assert.match(fresh.headers['x-request-id'], /^[0-9a-f-]{36}$/)

  const kept = await request(app).get('/api/health').set('X-Request-Id', 'abc-123').expect(200)
  assert.equal(kept.headers['x-request-id'], 'abc-123')

  const replaced = await request(app).get('/api/health').set('X-Request-Id', 'bad id!').expect(200)
  assert.notEqual(replaced.headers['x-request-id'], 'bad id!')
})

test('invalid bodies are a 422 that lists each problem', async () => {
  const { app } = setup()
  const res = await request(app).post('/api/projects').send({ name: '   ', owner: 'me' }).expect(422)
  assert.deepEqual(res.body.details.map((d) => d.field).sort(), ['body', 'name'])
  assert.equal(res.body.requestId, res.headers['x-request-id'])
})

test('a body that is not JSON is a 400', async () => {
  const { app } = setup()
  const res = await request(app)
    .post('/api/projects')
    .set('Content-Type', 'application/json')
    .send('{oops')
    .expect(400)
  assert.equal(res.body.error, 'Body is not valid JSON')
})

test('missing projects, tasks and routes are a 404', async () => {
  const { app } = setup()
  await request(app).get('/api/projects/42').expect(404)
  await request(app).get('/api/projects/42/tasks').expect(404)
  await request(app).post('/api/projects').send({ name: 'One' }).expect(201)
  await request(app).patch('/api/projects/1/tasks/7').send({ done: true }).expect(404)
  const res = await request(app).delete('/api/projects').expect(404)
  assert.equal(res.body.error, 'No route for DELETE /api/projects')
})

test('a failing store is a 500 with no internals in the reply', async () => {
  const broken = {
    ...createStore(),
    listProjects: async () => {
      throw new Error('database unreachable at 10.0.0.5')
    },
  }
  const { app, errors } = setup(broken)
  const res = await request(app).get('/api/projects').expect(500)
  assert.equal(res.body.error, 'Internal server error')
  assert.doesNotMatch(res.text, /database|10\.0\.0\.5|at /)
  assert.equal(errors.length, 1)
  assert.match(errors[0].stack, /database unreachable/)
  assert.equal(errors[0].requestId, res.body.requestId)
})
JS
npm pkg set scripts.test="node --test"
npm test

The last test is the one that justifies the structure. It replaces one store function with one that rejects, as a lost database connection would. The rejection travels from the async handler through Express 5 to the error handler with no catch in the route, the caller sees only the fixed message, and the fake logger receives the stack with the same request id.

node --test with no file names finds files ending in .test.js, among other patterns, so new test files are picked up as you add them.

Check it worked

The output lists six tests, each marked as passing, and ends with a summary that includes tests 6, pass 6 and fail 0.

Step 9 · Grow it and clean up

To add a resource, say members, repeat the pattern: a src/members/ folder with a store, schemas and a router factory, then one app.use('/api/members', membersRouter(store)) line in app.js above notFound. Validation, logging, request ids and error replies apply to it with no extra code. Shared checks that several routers need, such as authentication, become one more middleware file mounted on those routers.

When you are done, stop the server with Ctrl+C if it is running, then delete the demo folder. It holds only what you made here:

Bash
cd ~
rm -rf ~/express-structure-demo

Check it worked

Bash
ls ~/express-structure-demo 2>/dev/null || echo "removed"

The output is removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.