Skip to content
jshacks.dev
Patterns

Implement a service layer in an Express app

Implement a service layer in an Express app in JavaScript: handlers parse the request and a service holds the logic. Node.js 24.

1 min read
Summarize in AI

A route handler that holds business logic is hard to test and reuse. A service layer keeps the handler thin: it reads the request, calls a service function and sends the result.

JavaScript
import express from 'express';

// service: plain functions, no req or res
const orders = new Map([[1, { id: 1, total: 4000, status: 'paid' }]]);

function cancelOrder(id) {
  const order = orders.get(id);
  if (!order) return { error: 'not found', status: 404 };
  if (order.status !== 'paid') return { error: 'cannot cancel', status: 409 };
  order.status = 'cancelled';
  return { order };
}

// handler: translate HTTP to a service call and back
const app = express();
app.post('/orders/:id/cancel', (req, res) => {
  const result = cancelOrder(Number(req.params.id));
  if (result.error) return res.status(result.status).json({ error: result.error });
  res.json(result.order);
});

app.listen(3000);
Text
POST /orders/1/cancel  ->  200 {"id":1,"total":4000,"status":"cancelled"}
POST /orders/1/cancel  ->  409 {"error":"cannot cancel"}
POST /orders/9/cancel  ->  404 {"error":"not found"}

cancelOrder knows nothing about Express, so a test calls it with a number and checks the returned object. The handler maps the result to an HTTP status.

This uses Express 5 on Node.js 24; install it with npm install express. A service that grows several unrelated functions should split by feature, and services should return data or throw, never write to res.

Also inNode.js
Taggednode 24
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.