Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 43 ยท Building REST APIs

Controllers and Services

Split an Express API into routes, controllers and services, write async handlers, and learn how Express 5 forwards rejected promises to your error handler.

A first Express API usually puts everything in one file: the route, the validation, the database call and the response. That works for three endpoints. By thirty endpoints it is hard to read, hard to test and hard to change. The usual cure is to split the code into three layers, each with one job: routes, controllers and services.

This lesson shows what each layer does, how async handlers fit in, and what changed in Express 5 about errors thrown inside them. The real Express code is read-only here because npm is not available in your browser. The runnable examples use the small stand-in framework from Inside Express, extended with an express.json() body parser and automatic promise handling.

Three layers, three jobs

Who does what?

Route Maps a method and path to a controller function.
Controller Reads the request, calls a service, sends the response.
Service Holds business rules and talks to the data store.

Only the controller knows about req and res.

1 / 2

A route file only wires things together. It says "a GET to /todos/:id runs todoController.show" and nothing else.

A controller is the HTTP translator. It pulls values out of req (req.params.id, req.body, req.query), calls the service with plain JavaScript values, and turns the result into a status code and a JSON body. It should not contain business rules.

A service knows nothing about HTTP. It receives plain arguments such as an id or a data object, and returns plain results or throws. Because it never touches req or res, you can call it from a test, a background job or a command-line script.

What it looks like in real Express

This is the shape of a small real project. It is read-only here.

JavaScript
// routes/todos.js
import { Router } from 'express';
import * as todoController from '../controllers/todoController.js';

const router = Router();
router.get('/', todoController.index);
router.get('/:id', todoController.show);
router.post('/', todoController.create);
router.delete('/:id', todoController.destroy);
export default router;
JavaScript
// controllers/todoController.js
import * as todoService from '../services/todoService.js';

export async function show(req, res) {
  const todo = await todoService.find(Number(req.params.id));
  if (!todo) {
    return res.status(404).json({ error: 'Todo not found' });
  }
  res.json(todo);
}
JavaScript
// app.js
import express from 'express';
import todoRoutes from './routes/todos.js';

const app = express();
app.use(express.json());
app.use('/todos', todoRoutes);
export default app;

The router mounts under /todos, so each route inside only needs its own tail of the path. Modular Routing explains mounting in detail, and Project Setup shows where the folders live.

A runnable version

The stand-in has no Router, so the example mounts the controller functions directly on app. The layers are the same: a service with an in-memory Map, a controller object, and a few route lines.

Node.js Routes, controller and service

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.

Notice that todoService.create receives a plain object and returns a plain object. You could call it from a test with no HTTP at all, which is the main payoff of the split. Testing Express Apps builds on this.

Keep controllers thin

A good controller is short. A useful rule of thumb: if a controller function needs a comment to explain a business rule ("free users may only have five todos"), that rule belongs in the service.

Let the service throw errors that describe the problem (for example a NotFoundError), and let one central error handler turn them into status codes. Then controllers stop repeating if (!todo) return res.status(404)... everywhere. Error Handling shows exactly that pattern.

Also resist passing req or res into a service "just to be convenient". The moment you do, the service can no longer be called without a web server.

Async handlers

Almost every real handler is async, because databases, files and other services are asynchronous. An async function always returns a promise. If something inside it throws or rejects, the promise rejects.

What happens to that rejection depends on the Express version:

  • Express 5 (the current major version) notices when a handler or middleware returns a rejected promise and calls next(err) for you. The error reaches your error handler like any synchronous throw.
  • Express 4 ignored the returned promise. A rejection became an unhandled rejection: the request hung, and on modern Node the process could crash. Every async handler had to catch errors and call next(err) by hand, or be wrapped by a helper.
JavaScript
// Express 4 style: needed to avoid hanging requests
const asyncHandler = (fn) => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

router.get('/:id', asyncHandler(todoController.show));

In Express 5 you can drop the wrapper and write router.get('/:id', todoController.show) directly. The wrapper is harmless on Express 5, which is why you still see it in older tutorials and codebases you might maintain.

Forwarding only works for the promise a handler returns. If you start a promise and do not return or await it (db.save(x).then(...) without return), a rejection there is not forwarded. Always await your asynchronous work inside an async handler.

Seeing the forwarding

The next example makes the service fail on purpose. First the app behaves like Express 5: the stand-in forwards the rejected promise to the error handler. Then an app configured with promises: false (Express 4 behavior) is protected by the asyncHandler wrapper instead. Both end in the same JSON error response.

Node.js Rejected promises become next(err)

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.

Both runs print the todo for id 1 and a 500 error for id 99. Only the plumbing differs: Express 5 does it for you.

Organizing the files

There is no single required layout, but this one scales well:

TEXT
src/
  app.js              builds the app (no listen)
  server.js           calls app.listen
  routes/             one file per resource
  controllers/        one file per resource
  services/           business logic and data access
  middleware/         validation, auth, error handler

Small APIs can merge controllers into route files. Large ones often group by feature (todos/routes.js, todos/controller.js, todos/service.js) instead of by layer. Both are fine; what matters is that HTTP code and business code stay apart.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which layer should be the only one to use req and res?

    Controllers translate between HTTP and plain function calls. Services stay free of req and res so they can be reused and tested without a server.
  2. 2. In Express 5, what happens when an async route handler throws an error?

    Express 5 reacts to a rejected promise returned by a handler by calling next(err), so your error middleware runs.
  3. 3. Why do many older codebases wrap handlers in asyncHandler?

    Express 4 ignored the promise a handler returned, so rejections had to be caught and passed to next(err) manually.
  4. 4. Where is the best place for the rule "a user may own at most five todos"?

    Business rules belong in the service, so every caller of that service follows them.

Summary

  • Routes wire paths to controllers, controllers translate HTTP, services hold the logic.
  • Services receive plain values and never see req or res.
  • Express 5 forwards rejected promises from handlers to your error handler; Express 4 needed a wrapper.
  • Always await or return asynchronous work so errors can be forwarded.
  • On this site the framework is a stand-in; the layering ideas carry over unchanged to real Express.

Next: Validating Input.