Skip to content
Tutorials Center
My learning

Topics

Lesson 94 of 133 ยท Frameworks and Ecosystem

Project Structure and Architecture

Learn how to structure a Node.js project - layers, feature folders, dependency injection, config, keeping HTTP separate from domain code, testing seams and monorepos.

Node.js gives you no required folder layout. That freedom is pleasant for a 50-line script and dangerous for a 50,000-line service. Without a plan, a project drifts into one giant file, or into a maze where every module imports every other module and nothing can be tested without a database and a web server.

Good structure is not about fashion. It answers practical questions: where does a new feature go? Which code can I change without breaking the rest? How do I test business rules without starting a server? This lesson shows a small number of ideas that answer those questions, and then builds a complete (in-memory) application layout you can run.

Start simple, grow on purpose

For a script or a tiny tool, one file is correct. Introduce structure when it hurts: when a file passes a few hundred lines, when two people edit the same file, or when you cannot test something. A typical first layout for a small service looks like this:

TEXT
my-service/
  package.json
  src/
    server.js        # starts the app: wires everything together
    app.js           # builds the HTTP handler (no listen() here)
    config.js        # reads environment variables
    routes/          # HTTP layer
    services/        # business rules
    repositories/    # data access
  test/
  .env.example

Everything in this lesson is a way of deciding what belongs in each of those folders, and which way the imports are allowed to point.

Layers: separate what changes for different reasons

The classic split has three layers:

  1. HTTP (transport) layer: parses the request, calls a service, turns the result into a response. It knows about status codes, headers and JSON. It knows nothing about SQL.
  2. Service (domain) layer: the business rules: "an order needs at least one item", "a coupon can be used once". It is plain JavaScript functions and classes. It does not know that HTTP exists.
  3. Data (repository) layer: reads and writes storage. It hides whether the data lives in SQLite, PostgreSQL or an array.

The rule that makes layers useful is the direction of dependency: HTTP calls services, services call repositories, never the other way. If a service imports req or res, you can no longer call it from a command-line script, a queue worker or a test without faking a web request. If a repository decides what HTTP status to return, the same problem appears one layer down.

A quick test of a layer boundary: could you reuse this function unchanged from a CLI tool? If not, something from the web layer has leaked into it.

Business code that knows nothing about HTTP

Here is a tiny domain service. It takes plain values and throws meaningful domain errors. There is no req, no res, no database client, just rules.

Node.js A service with no knowledge of HTTP

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.

Look at the signature: createOrderService({ orders }). The service does not import a database module; it receives what it needs. That brings us to dependency injection.

Dependency injection without a framework

Dependency injection (DI) sounds heavy but means one simple thing: a module is given its collaborators instead of reaching for them. In Node.js the lightest form is a factory function (as above) or a class constructor that takes its dependencies as arguments. The code that creates the real objects and connects them is called the composition root, and it lives in exactly one place near the program's entry point.

Why bother? Because you can hand a service a fake repository in a test, a real one in production, and a logging wrapper in staging, without touching the service. Compare with a hard-wired import:

JavaScript
// Hard to test: the service always uses the real database module.
import { db } from '../db.js';
export function place(order) {
  return db.insert('orders', order);
}

With DI there is no hidden global. You can see in the function signature what it depends on. This also removes a class of bugs where importing a module has side effects (connecting to a database) just because a test imported something else.

Node.js Injecting a fake to test the rules

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.

Passing the clock in (clock: () => new Date(...)) is a very useful habit. Code that calls new Date() or Math.random() directly is hard to test; code that is given a clock is easy.

Layout by layer or by feature?

There are two common ways to arrange folders.

By layer groups files by technical role:

TEXT
src/
  controllers/  orders.js  users.js  products.js
  services/     orders.js  users.js  products.js
  repositories/ orders.js  users.js  products.js

By feature (also called vertical slices or modules) groups by what the code is for:

TEXT
src/
  orders/    routes.js  service.js  repository.js  orders.test.js
  users/     routes.js  service.js  repository.js  users.test.js
  products/  routes.js  service.js  repository.js  products.test.js
  shared/    config.js  logger.js  errors.js

For anything beyond a small API, feature folders usually age better. When you work on orders you open one folder, deleting a feature means deleting a folder, and the boundaries between features are visible. The layers still exist inside each feature; you have just changed the first level of the tree. A sensible rule is: features may use shared/, and a feature may talk to another feature only through that feature's public functions (an index.js that exports what others may use), not by reaching into its internals.

Configuration in one place

Read environment variables once, validate them, and export a plain object. Do not scatter process.env.X through the code base: it hides what the app needs, and a typo fails silently as undefined. The details of secrets and .env files are in Secrets and Configuration; here is the structural point.

Node.js A config module that fails fast

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.

The function takes env as an argument and the real process.env is passed only in the entry file. It checks everything in one go, reports all problems at once, and refuses to start with a bad configuration: far better than discovering a missing variable the first time a rarely-used route runs.

Keep HTTP at the edge

The HTTP layer should be thin. Its job is translating: parse input, call a service, translate the result or the error. Mapping domain errors to status codes in one place keeps services clean and keeps the API consistent.

A convenient trick is to build the handler without calling listen(). Then app.js exports something you can call in tests, and only server.js binds a port. We use Node's built-in http module here; the idea is identical in Express (see Express and Minimal Frameworks).

Node.js A thin HTTP layer that maps domain errors to statuses

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.

The service raised TITLE_REQUIRED without knowing about status 400; the HTTP layer made that decision. If you later add a command-line interface, it can call the same todoService and print a message instead.

MVC in a Node.js web app

Many Express tutorials and nearly every framework in other languages (Rails, Laravel, Django, Spring) organize code as MVC: models, views and controllers. It is the same layering idea in different words, with names that are worth recognizing:

MVC part What it is Layer in this lesson
Model Data and the rules about it: a Post with validation and queries Services and repositories
View How a result is presented: an HTML template or a JSON serializer The response-building part of the HTTP layer
Controller Receives a request, asks the model, picks a view The thin HTTP handlers
Routes The table that says which URL and method calls which controller The HTTP layer's entry point

In an Express project it looks like this:

TEXT
src/
  routes/posts.js          # router.get('/', posts.index); router.post('/', posts.create)
  controllers/posts.js     # index(req, res), show(req, res), create(req, res)
  models/post.js           # Post.all(), Post.find(id), Post.create(data) + validation
  views/posts/index.ejs    # HTML (or a serializer function for JSON APIs)
  app.js                   # wires middleware and routers, exports the app
  server.js                # app.listen(...)

The request flows one way: route, controller, model, back to the controller, then the view.

flowchart LR
    R["Request"] --> Ro["Route table"]
    Ro --> C["Controller"]
    C --> M["Model"]
    M --> C
    C --> V["View"]
    V --> Re["Response"]

The controller is the conductor: it never contains business rules or markup.

Run it. The mini application below has all four parts in one file so you can read the flow top to bottom. In a real project each block would be its own file under the folder shown above.

Node.js A complete tiny MVC app: routes, controllers, model and view

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 what each part is not allowed to do. The model returns plain data or a list of errors and has no idea that HTTP exists, so a CLI could call Post.create too. The view only formats (and escapes). The controller has no if about business rules: it calls the model and chooses between views. Because of that, the interesting rules can be tested without starting a server.

MVC has two well-known failure modes. A fat controller accumulates validation, calculations and queries until nobody can reuse them; the cure is to move them into the model or into a service. A fat model that also sends email and talks to payment providers becomes impossible to test; the cure is to give those collaborators their own modules and inject them. For JSON APIs the "view" is simply a serializer function that chooses which fields leave the system, and for server-rendered pages it is a template, as in Template Engines: EJS. Whether you call the layers MVC or "routes, services, repositories" matters much less than keeping the arrows pointing one way.

Testing seams

A seam is a place where you can substitute behavior without changing the code under test. DI creates seams: repositories, clocks, ID generators, HTTP clients, mailers. Design for them early:

  • Pass in anything non-deterministic (time, randomness, IDs).
  • Pass in anything slow or external (database, network, file system, email).
  • Keep pure logic (calculations, validation) in plain functions with no dependencies at all. They are the easiest and most valuable to test.

Test layers differently. Domain rules get many fast unit tests with fakes. The HTTP layer gets fewer tests that exercise routing and status codes (see Testing HTTP Servers and CLIs). Repositories get a few tests against a real database, such as in-memory SQLite (see SQLite in Node.js). This balance is sometimes drawn as a test pyramid: many small tests at the bottom, a few broad ones at the top.

Module boundaries and circular imports

As a project grows, watch the import graph. Two warning signs are circular imports (a.js imports b.js which imports a.js) and a utils/ folder that everything imports. Cycles often mean two modules are really one concept, or that a shared piece should be extracted into a third module. ES modules handle some cycles through live bindings (see ES Modules), but a cycle that works today breaks mysteriously after a refactor.

Package.json can also enforce boundaries. The imports field creates private aliases that only your own package can use:

JSON
{
  "name": "my-service",
  "type": "module",
  "imports": {
    "#shared/*": "./src/shared/*.js",
    "#orders": "./src/orders/index.js"
  }
}

With that, import { logger } from '#shared/logger' works from any depth, and you avoid long ../../../ paths. See package.json in Depth for the details of imports and exports.

Monorepos

When you have several related packages (an API, a worker, a shared library, a web client), you can keep them in one repository, a monorepo. npm, pnpm and Yarn support this through workspaces:

JSON
{
  "name": "acme",
  "private": true,
  "workspaces": ["apps/*", "packages/*"]
}
TEXT
acme/
  package.json
  apps/
    api/        package.json  src/
    worker/     package.json  src/
  packages/
    domain/     package.json  src/    # business rules shared by api and worker
    config/     package.json  src/

Running npm install at the root links the workspace packages into each other, so apps/api can import '@acme/domain' and see local changes immediately. A monorepo makes sharing code and making cross-cutting changes easy; the price is slower tooling as it grows, so large ones add task runners that only rebuild what changed. For a single service, a monorepo is not needed. Start with one package and split when a second deployable thing appears.

Putting it together: an entry point

Finally, the pieces meet in one small file. Everything above converges into a composition root like this (read-only, because it spans many files):

JavaScript
// src/server.js
import { loadConfig } from './shared/config.js';
import { createLogger } from './shared/logger.js';
import { createDatabase } from './shared/database.js';
import { createOrderRepository } from './orders/repository.js';
import { createOrderService } from './orders/service.js';
import { createApp } from './app.js';
import http from 'node:http';

const config = loadConfig(process.env);
const logger = createLogger({ level: config.logLevel });
const database = createDatabase(config.databaseUrl);

const orderService = createOrderService({ orders: createOrderRepository(database) });
const server = http.createServer(createApp({ orderService, logger }));

server.listen(config.port, () => logger.info({ port: config.port }, 'listening'));

Notice that every create... call is explicit. There is no magic; you can read the file top to bottom and know how the application is assembled. For larger systems, DI containers (such as awilix or tsyringe) automate this wiring, but plain factories carry you a very long way.

Habits that keep a codebase healthy

  • Name things after the business, not the technology (orders/, not mysqlStuff/).
  • Keep files small and modules focused; export as little as possible.
  • Put side effects (listening, connecting, reading env) in the entry point, not at import time.
  • Prefer composition and plain functions over deep class hierarchies.
  • Write the folder structure down in a short README so newcomers know where things go.
  • Refactor structure when a change feels harder than it should, not as a big up-front design exercise.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a layered Node.js application, which direction should dependencies point?

    Outer layers depend on inner ones. The domain should not know about HTTP, so the web layer calls services and services call data access.
  2. 2. What is the composition root?

    It is the one place that knows about all concrete parts, such as the real repository and the real logger, and passes them to the code that needs them.
  3. 3. Why does accepting a clock function as a dependency help?

    Injecting the clock is a seam. Tests can return a fixed date instead of depending on the real time.
  4. 4. Why is it better to create the HTTP handler in app.js and call listen() only in server.js?

    Separating the creation of the app from starting it makes the app easy to test, for example on port 0, or to reuse in other runtimes.
  5. 5. What is a good reason to prefer feature folders over layer folders in a growing project?

    Working on one feature touches one folder, and deleting or moving a feature is easy. Layers still exist inside each feature.

Summary

  • Add structure when it hurts, not before; a small script can stay a single file.
  • Separate HTTP, business rules and data access, and let dependencies point inward only.
  • Pass collaborators in (factories or constructors) instead of importing hard-wired singletons; assemble everything in a single composition root.
  • Load and validate configuration once, fail fast, and pass the config object down.
  • Keep the HTTP layer thin: parse, call a service, map errors to status codes in one place.
  • Design testing seams for time, randomness, IDs and external systems.
  • Prefer feature folders for larger projects, use imports aliases, and consider workspaces only when you really have several packages.

Next: Building and Bundling