Why structure matters
In the last lesson our whole To-Do API lived in one file. That's fine for 30 lines. But a real app has login, validation, a database, error handling⦠Put it all in one file and you get a 1,000-line monster nobody wants to touch. A good structure means you always know where to look, and every file has one job.
The restaurant again
| Layer | Restaurant job | In our To-Do API |
|---|---|---|
| Routes | The menu: lists what you can order | POST /api/tasks β task.create |
| Middleware | The doorman and the order checker | Logged in? Is the title filled in? |
| Controller | The waiter: takes the order, brings the plate | Reads req, calls the service, sends res |
| Service | The chef: does the actual cooking | Saves the task in the database |
| Prisma / database | The store room | PostgreSQL tables |
The folder structure we'll use
tasks-api/ βββ prisma/ β βββ schema.prisma # what the database tables look like β βββ migrations/ # history of table changes (made by Prisma) βββ src/ β βββ server.ts # starts the server (tiny) β βββ app.ts # builds the app: middleware + routes β βββ config/ β β βββ env.ts # reads and checks settings from .env β βββ lib/ β β βββ prisma.ts # the one database client β βββ middlewares/ β β βββ auth.ts # "are you logged in?" β β βββ validate.ts # "is the data correct?" β β βββ error-handler.ts # one place that turns errors into responses β βββ utils/ β β βββ http-error.ts # an error that carries a status code β βββ modules/ # one folder per feature β βββ auth/ β β βββ auth.routes.ts # URLs β controller functions β β βββ auth.controller.ts # reads req, calls service, sends res β β βββ auth.service.ts # the real work + database β β βββ auth.schema.ts # rules for the incoming data (Zod) β βββ tasks/ β βββ task.routes.ts β βββ task.controller.ts β βββ task.service.ts β βββ task.schema.ts βββ .env # your secrets (never committed) βββ .env.example # the same keys with fake values (committed) βββ package.json βββ tsconfig.json
This is called a feature-based (or modular) structure: everything about tasks lives in modules/tasks. When you add a new feature, say comments, you add a modules/comments folder with the same four files. Nothing else moves.
The journey of one request
Here's what happens when the app sends POST /api/tasks with { "title": "Buy milk" }:
- 1
πͺ
app.ts
Global middleware runs: security headers, CORS, express.json() reads the body.
- 2
πΊοΈ
task.routes.ts
Finds the route POST / and the middleware to run first.
- 3
π
auth middleware
Checks the login token. No token? Stop here with 401.
- 4
β
validate middleware
Checks the body against the Zod schema. Empty title? Stop with 400.
- 5
π§βπ³
controller β service
Controller calls taskService.createTask(); the service saves it with Prisma.
- 6
π¦
response
Controller sends 201 + the new task. Any error goes to the error handler instead.
The four files of a feature
1. Routes: just the menu
A routes file only connects URLs to controller functions, with any middleware in between. Read it like a table of contents:
import { Router } from "express";
import * as task from "./task.controller";
import { validate } from "../../middlewares/validate";
import { requireAuth } from "../../middlewares/auth";
import { createTaskSchema, updateTaskSchema } from "./task.schema";
export const taskRouter = Router();
taskRouter.use(requireAuth); // every task route needs a logged-in user
taskRouter.get("/", task.list); // GET /api/tasks
taskRouter.get("/:id", task.getOne); // GET /api/tasks/5
taskRouter.post("/", validate(createTaskSchema), task.create); // POST /api/tasks
taskRouter.patch("/:id", validate(updateTaskSchema), task.update);// PATCH /api/tasks/5
taskRouter.delete("/:id", task.remove); // DELETE /api/tasks/52. Controller: speaks HTTP
The controller reads what it needs from the request, calls the service, and picks the status code. No database code here:
import type { Request, Response } from "express";
import * as taskService from "./task.service";
import { HttpError } from "../../utils/http-error";
// Controllers read the request, call a service, and send the response. Nothing else.
function readId(req: Request) {
const id = Number(req.params.id);
if (!Number.isInteger(id) || id < 1) throw new HttpError(400, "Invalid task id");
return id;
}
export async function list(req: Request, res: Response) {
const page = Math.max(1, Number(req.query.page) || 1);
const limit = Math.min(50, Math.max(1, Number(req.query.limit) || 10));
res.json(await taskService.listTasks(res.locals.userId, page, limit));
}
export async function getOne(req: Request, res: Response) {
res.json(await taskService.getTask(res.locals.userId, readId(req)));
}
export async function create(req: Request, res: Response) {
const task = await taskService.createTask(res.locals.userId, req.body);
res.status(201).json(task);
}
export async function update(req: Request, res: Response) {
res.json(await taskService.updateTask(res.locals.userId, readId(req), req.body));
}
export async function remove(req: Request, res: Response) {
await taskService.deleteTask(res.locals.userId, readId(req));
res.status(204).send();
}3. Service: does the work
The service is where the real logic lives. Notice it never touches req or res: it takes plain values and returns plain values. You'll see the full service in the CRUD lesson.
4. Schema: the rules for incoming data
The schema describes what valid data looks like, using a library called Zod. We'll use it in the CRUD lesson. Install it now with bun add zod.
Middleware: the guards at the door
A middleware is a function with three inputs: req, res and next. It either stops the request (by sending a response or throwing an error) or calls next() to let it continue. Our validation middleware is a great example:
import type { Request, Response, NextFunction } from "express";
import type { ZodType } from "zod";
// Checks req.body against a Zod schema. Bad data never reaches your controller.
export function validate(schema: ZodType) {
return (req: Request, res: Response, next: NextFunction) => {
const result = schema.safeParse(req.body);
if (!result.success) {
return res.status(400).json({
error: "Invalid input",
details: result.error.issues.map((i) => ({ field: i.path.join("."), message: i.message })),
});
}
req.body = result.data; // the cleaned, typed data
next();
};
}One place for all errors
Instead of writing try/catch in every controller, services simply throw an error with a status code, and one error handler at the end turns it into a clean response:
// An error that knows which HTTP status code to send back.
export class HttpError extends Error {
status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
}import type { Request, Response, NextFunction } from "express";
import { HttpError } from "../utils/http-error";
// 404 for any URL that no route matched.
export function notFound(req: Request, res: Response) {
res.status(404).json({ error: `Route ${req.method} ${req.path} not found` });
}
// The one place every error ends up. Express 5 sends errors from async code here automatically.
export function errorHandler(err: unknown, req: Request, res: Response, next: NextFunction) {
if (err instanceof HttpError) {
return res.status(err.status).json({ error: err.message });
}
if (err instanceof SyntaxError && "body" in err) {
return res.status(400).json({ error: "Request body is not valid JSON" }); // express.json() couldn't read it
}
console.error(err); // log the real problem for you...
res.status(500).json({ error: "Something went wrong" }); // ...but never show it to users
}app.ts and server.ts
app.ts builds the app in three blocks, and the order matters: global middleware first, then routes, then the βnot foundβ and error handlers last.
import express from "express";
import helmet from "helmet";
import cors from "cors";
import { authRouter } from "./modules/auth/auth.routes";
import { taskRouter } from "./modules/tasks/task.routes";
import { errorHandler, notFound } from "./middlewares/error-handler";
export const app = express();
// 1. Middleware that runs on every request
app.use(helmet()); // safe HTTP headers
app.use(cors()); // allow browsers on other sites to call the API
app.use(express.json()); // turn JSON request bodies into req.body
// 2. Routes
app.get("/health", (req, res) => {
res.json({ status: "ok" });
});
app.use("/api/auth", authRouter);
app.use("/api/tasks", taskRouter);
// 3. Nothing matched, or something broke
app.use(notFound);
app.use(errorHandler);import { app } from "./app";
import { env } from "./config/env";
app.listen(env.PORT, () => {
console.log(`API running on http://localhost:${env.PORT}`);
});π‘server.ts only starts the app. Tests can import app.ts without opening a real port.
helmet adds safe HTTP headers and cors allows browser apps on other websites to call your API. Install them with bun add helmet cors and bun add -d @types/cors.
Check your settings once, at startup
Instead of reading process.env all over the code, read it in one file and check it. If a setting is missing, the app stops immediately with a clear message, instead of crashing later in a confusing way:
import { z } from "zod";
// Check every setting once, at startup. If one is missing, the app stops with a clear message.
const envSchema = z.object({
PORT: z.coerce.number().default(3000),
DATABASE_URL: z.string().min(1),
JWT_SECRET: z.string().min(16, "JWT_SECRET must be at least 16 characters"),
});
export const env = envSchema.parse(process.env);Key takeaways
- βA clear structure means every file has one job and you always know where code goes.
- βWe use a feature-based layout: modules/<feature> with routes, controller, service and schema files.
- βMiddleware runs in order and can stop a request or pass it on with next().
- βA single error handler at the end turns thrown errors into clean JSON responses.
- βapp.ts builds the app, server.ts starts it, config/env.ts checks the settings at startup.
Frequently asked questions
What is the best folder structure for an Express API?
Group code by feature (auth, tasksβ¦) and split each feature into routes, controller, service and schema files. Shared things like middleware, config and the database client get their own folders. This is what we use in this course.
What is the difference between a controller and a service?
The controller deals with HTTP: it reads req and sends res. The service holds the actual work and talks to the database, without knowing anything about req or res. That makes services easy to reuse and test.
What is middleware in Express?
A function that runs before your route handler, in the middle of the request. It can check something (is the user logged in? is the data valid?) and either stop the request with an error or call next() to continue.
Why split app.ts and server.ts?
app.ts builds the app (middleware and routes); server.ts only starts listening. Tests can import the app without starting a real server, and the startup code stays tiny.
Do I need this structure for a small project?
For a 50-line toy, no. As soon as you have a database and more than a couple of routes, yes: it stops files from growing into a 1,000-line mess and tells everyone where each kind of code lives.
π§ Quick check: folder structure
1. Where does the code that saves a task in the database belong?
2. Which file should read req.params.id and send res.status(201)?
3. A middleware has checked the user is logged in. What does it call to continue?
4. Where must the error handler be added?
Checking your accessβ¦