Backend Project Structure

The folder layout that keeps routes, business logic and data access apart as a backend grows.

What is it?

A backend with two or three routes fits in one file. Add validation, error handling, a database and a dozen endpoints, and that file grows to hundreds of lines mixing three concerns: parsing HTTP requests, deciding what should happen, and talking to the database.

Project structure splits those concerns into folders, so each piece of code has one job and a predictable home. A common layout:

  • routes/: which URLs exist.
  • controllers/: turn a request into a plain function call and a response.
  • services/: the business logic.
  • models/: talking to the database.

Explain like I'm 10

Think of a restaurant: the host (routes) decides which table a guest goes to, the server (controller) takes the order and carries it back, the chef (service) cooks from the recipe, and the pantry (model) holds the ingredients. One overworked person could do it all, but splitting the roles lets the kitchen serve more than a few tables without chaos.

Examples

Before: everything in one file

// server.js — every concern tangled together
app.post("/users", async (req, res) => {
  if (!req.body.email || !req.body.email.includes("@")) {
    return res.status(400).json({ error: "invalid email" });
  }
  const existing = await db.query("SELECT * FROM users WHERE email = $1", [req.body.email]);
  if (existing.rows.length > 0) {
    return res.status(409).json({ error: "email taken" });
  }
  const result = await db.query(
    "INSERT INTO users (email) VALUES ($1) RETURNING *",
    [req.body.email]
  );
  res.status(201).json(result.rows[0]);
});

Validation, business rules and raw SQL are crammed into the route. Fine for one endpoint, unmanageable for fifty.

After: split across layers

// routes/users.js
router.post("/users", usersController.create);

// controllers/usersController.js
async function create(req, res) {
  const user = await usersService.createUser(req.body.email);
  res.status(201).json(user);
}

// services/usersService.js
async function createUser(email) {
  if (!email.includes("@")) throw new ValidationError("invalid email");
  if (await usersModel.findByEmail(email)) throw new ConflictError("email taken");
  return usersModel.insert(email);
}

// models/usersModel.js
function findByEmail(email) {
  return db.query("SELECT * FROM users WHERE email = $1", [email]);
}

Each file now has one job. The route maps a URL to a controller, the controller only translates HTTP in and out, the service holds the rule ('emails must be unique'), and the model is the only place that knows SQL.

The full folder tree, and how it actually gets run

my-api/
├── package.json          # scripts.dev = "node src/server.js"
├── src/
│   ├── server.js          # entry point: starts the app, calls app.listen()
│   ├── app.js             # creates the Express app, wires up middleware + routes
│   ├── routes/
│   │   └── users.js
│   ├── controllers/
│   │   └── usersController.js
│   ├── services/
│   │   └── usersService.js
│   ├── models/
│   │   └── usersModel.js
│   └── config/
│       └── db.js          # database connection setup
└── .env                   # DATABASE_URL, PORT, etc.

# Run it with:
$ npm run dev

server.js is the one file that actually runs. Everything else (app.js and the folders below) is code that server.js requires, directly or indirectly. npm run dev is a package.json shortcut for node src/server.js, so nobody has to remember the entry-file path.

How it works

A request flows down through the layers and the response flows back up. The route matches a URL to a controller. The controller takes what it needs from the request and calls a service. The service applies business rules and calls a model for data. The model is the only layer that knows how data is stored.

Each layer only talks to the one directly below it. That's why you can change one layer (like swapping databases) without rewriting the others.

Route  →  Controller  →  Service  →  Model  →  Database
(URL)     (HTTP in/out)  (business    (data
                          rules)       access)

Why does it exist?

Without structure, HTTP handling, business rules and database queries get tangled in the same functions. The code becomes:

  • Hard to test: you can't test a rule without faking a whole HTTP request.
  • Hard to change: a database swap touches every route.
  • Hard to navigate: there's no predictable place for each kind of logic.

When to use it

Use a layered structure once a project has more than a handful of endpoints, or once the same logic (like "is this email taken?") is needed in more than one place.

When not to use it

For a tiny prototype, quick script, or two or three endpoints, four folders are often pure overhead. One tidy file is easier to follow than five nearly empty ones. Add structure when you feel the pain, not before.

Common mistakes

  • Putting raw database queries in route handlers or controllers, defeating the point of a data-access layer.

  • Letting controllers grow their own business logic instead of using a service, so the same rule is duplicated across controllers.

  • Using the full layered structure for a two-endpoint prototype, adding indirection before there's real complexity.

  • Not knowing which file is the entry point, and guessing how to start the app instead of checking package.json's scripts.

Practice exercises

  1. Easy:

    Which layer (route, controller, service or model) should hold a function that checks whether a discount code has expired? Why?

  2. Medium:

    Take a route handler that queries a database and formats a JSON response, and split it into a controller and a model function.

  3. Hard:

    Explain the trade-off between a full layered structure and a single file for a 3-endpoint prototype, and describe the signal that it's time to split it up.

Interview questions

Why split a backend project into routes, controllers, services, and models instead of one file?

To separate concerns: each layer has one job and a predictable place, so the code is easier to test, change and navigate as it grows.

What's the difference between a controller and a service?

A controller turns an HTTP request into a plain function call and shapes the response. A service holds the business logic, independent of HTTP.

How does a command like `npm run dev` know which file to actually run?

It's a shortcut in the scripts section of package.json that points at the real entry file: the one that calls app.listen() and starts the server.

Which single layer should be the only one that knows actual SQL or database queries directly, and why does that matter?

The model layer. With database access in one layer, a change in storage or queries only touches that layer, instead of scattered queries across routes, controllers and services.

A controller function directly runs `db.query(...)` itself instead of calling a service. What problem does this create if the team later switches databases?

Database-specific code is now spread across every controller that queries directly. Switching databases means finding and rewriting all of them, not just the model layer.

Why is it bad practice for the same business rule, like "email must be unique," to be duplicated inside multiple controllers?

When the rule changes or gets a bug fix, every copy must be found and updated. Missing one makes endpoints that should enforce the same rule behave differently.

What does it mean for each layer to "only talk to the one directly below it," and why does that make swapping a layer out easier?

Routes only call controllers, controllers only call services, and services only call models; no layer skips a level. So replacing one layer (like changing databases in the model) doesn't ripple upward, because the layers above depend only on its interface, not its internals.

What's the difference between `server.js` and `app.js` in the example project structure?

app.js creates the Express app and wires up middleware and routes. server.js is the entry point that imports app.js and calls app.listen(). Keeping them apart lets you import and test the app without starting a live server.

A new developer isn't sure which file is a project's real entry point. Where should they look?

In the scripts section of package.json, at the script that runs the app (usually dev or start). It names the entry file directly, so nobody has to guess.

Why does testing a business rule get harder when that rule lives directly inside a route handler mixed with HTTP-specific code?

You'd have to fake a whole HTTP request and response to test a rule that has nothing to do with HTTP. Moving the rule into a plain service function lets you test it with ordinary calls and inputs.

A two-endpoint prototype adopts the full routes/controllers/services/models structure from day one. What's the likely downside?

With so little logic, the structure only adds indirection (jumping between four or five nearly empty files) with no real complexity to justify it. One tidy file would be easier to follow.

What signal tells a team it's time to move from a single-file backend to a layered structure?

When the same logic is needed in more than one place, or the file has grown so unrelated concerns (HTTP handling, business rules, database queries) are hard to tell apart or navigate.

Why does the route layer contain no logic in the layered example, and why keep it that thin?

Its one job is mapping URLs and methods to controllers. Keeping it thin means you can scan which endpoints exist at a glance, without business logic in the way.

If `usersService.createUser` throws a `ValidationError` and the controller doesn't catch it, what happens to the request?

The error propagates uncaught. Depending on the error-handling setup, that usually means an unhandled rejection or a generic 500 instead of the intended specific error. So controllers (or error-handling middleware) usually need to catch expected service errors and translate them.

What can a service function do that a model function specifically should not, and vice versa?

A service applies business rules (like checking an email is taken before creating a user). A model only reads and writes data. A model making business decisions, or a service writing raw SQL, blurs the boundary the layers exist to keep.

Why is `usersService.createUser` described as "reusable from anywhere, not tied to HTTP"? What does that buy you?

It takes plain arguments and returns plain results instead of using req or res. So a controller, background job, CLI script or test can call it wherever the same rule is needed, without any HTTP machinery.

What does the model layer being "the only file that knows how a user is actually stored" imply about switching from PostgreSQL to MongoDB, or adding caching?

The change stays inside the model layer. Services and controllers don't change, because they rely only on the model's function signatures (like findByEmail), not how they're implemented.

A service throws an error because a requested resource doesn't exist. Whose job is it to turn that into an HTTP 404 — the service or the controller?

The controller's. The service shouldn't know about HTTP status codes, since it should be reusable outside HTTP. The controller translates a business outcome ("not found") into the right HTTP response.

Why might a small internal tool or one-off script deliberately not adopt this layered structure at all?

With little reused logic and only a few operations, maintaining separate route, controller, service and model files costs more than it gives. One simple file is faster to write and easier to follow for something small and short-lived.

What's the practical risk of not knowing your project's real entry point when debugging unexpected behavior?

You might edit or reason about a file that never runs, or start the app in a way that skips config or middleware the real entry point sets up. The results won't match what you changed.