TExcelTAD
Home › Express & NestJS › Project Structure

Project Structure

Express gives you no folder layout. That's liberating for a 50-line service and chaotic for a 50-endpoint one. This lesson presents a layout that scales, based on one principle: separate HTTP concerns from business logic from data access.

Layers

Layer Knows about Does NOT know about
Routes / controllers req, res, status codes, validation of input shape SQL, how data is stored
Services business rules ("a user can have at most 5 projects") HTTP, req/res
Repositories / stores the database or external API HTTP, business rules

Each layer only calls the one below it. Services become plain functions you can unit-test without HTTP, and swapping PostgreSQL for something else only touches repositories.

A folder layout

Group by feature (all bookmark code together) rather than by technical type (all controllers together). Features stay small and easy to delete or move:

text
bookmarks-api/
├── src/
│   ├── app.js                 createApp(deps): middleware + routers, no listen()
│   ├── server.js              loads config, builds deps, calls listen()
│   ├── config.js              reads and validates process.env
│   ├── middleware/
│   │   ├── authenticate.js
│   │   ├── error-handler.js
│   │   └── request-logger.js
│   ├── lib/
│   │   └── http-error.js      class HttpError
│   └── features/
│       ├── bookmarks/
│       │   ├── bookmarks.routes.js      Router: parse req, call service, send res
│       │   ├── bookmarks.service.js     rules: validate URL, enforce limits
│       │   ├── bookmarks.repository.js  data access
│       │   └── bookmarks.test.js
│       └── users/
│           └── …
├── test/                      cross-feature / e2e tests
├── .env.example
├── Dockerfile
└── package.json

The layers in code

Here the three layers live in one file so you can run it, but each block maps to one file in the layout above:

node · try it yourself
const express = require('express');

// ---- lib/http-error.js
class HttpError extends Error {
  constructor(status, message) { super(message); this.status = status; }
}

// ---- features/bookmarks/bookmarks.repository.js  (data access only)
function createBookmarkRepository() {
  const rows = [];
  return {
    async findByUser(userId) { return rows.filter((r) => r.userId === userId); },
    async insert(row) { const saved = { id: rows.length + 1, ...row }; rows.push(saved); return saved; },
  };
}

// ---- features/bookmarks/bookmarks.service.js  (business rules, no HTTP)
function createBookmarkService({ repo, maxPerUser }) {
  return {
    list: (userId) => repo.findByUser(userId),
    async add(userId, url) {
      if (!URL.canParse(url)) throw new HttpError(422, 'url must be a valid URL');
      const existing = await repo.findByUser(userId);
      if (existing.length >= maxPerUser) throw new HttpError(409, `limit of ${maxPerUser} bookmarks reached`);
      return repo.insert({ userId, url: new URL(url).href });
    },
  };
}

// ---- features/bookmarks/bookmarks.routes.js  (HTTP only)
function bookmarkRoutes({ service }) {
  const router = express.Router();
  router.get('/', async (req, res) => res.json(await service.list(req.userId)));
  router.post('/', async (req, res) => res.status(201).json(await service.add(req.userId, req.body?.url)));
  return router;
}

// ---- app.js  (composition)
function createApp({ service }) {
  const app = express();
  app.use(express.json());
  app.use((req, res, next) => { req.userId = req.get('X-User') ?? 'anon'; next(); }); // stand-in for auth
  app.use('/bookmarks', bookmarkRoutes({ service }));
  app.use((err, req, res, next) => res.status(err.status ?? 500).json({ error: err.message }));
  return app;
}

// ---- server.js  (wiring)
const service = createBookmarkService({ repo: createBookmarkRepository(), maxPerUser: 2 });
const server = createApp({ service }).listen(0, async () => {
  const base = `http://localhost:${server.address().port}/bookmarks`;
  const add = async (url) => {
    const res = await fetch(base, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-User': 'ana' }, body: JSON.stringify({ url }) });
    console.log(res.status, await res.text());
  };
  await add('https://expressjs.com');
  await add('not a url');
  await add('https://nestjs.com');
  await add('https://nodejs.org');
  const list = await fetch(base, { headers: { 'X-User': 'ana' } });
  console.log(list.status, await list.text());
  server.close();
});
201 {"id":1,"userId":"ana","url":"https://expressjs.com/"}
422 {"error":"url must be a valid URL"}
201 {"id":2,"userId":"ana","url":"https://nestjs.com/"}
409 {"error":"limit of 2 bookmarks reached"}
200 [{"id":1,"userId":"ana","url":"https://expressjs.com/"},{"id":2,"userId":"ana","url":"https://nestjs.com/"}]

Testing the service without HTTP

Because the service only depends on a repo object, a test can pass a fake one and check the business rule directly:

node · try it yourself
class HttpError extends Error {
  constructor(status, message) { super(message); this.status = status; }
}

function createBookmarkService({ repo, maxPerUser }) {
  return {
    async add(userId, url) {
      if (!URL.canParse(url)) throw new HttpError(422, 'url must be a valid URL');
      if ((await repo.findByUser(userId)).length >= maxPerUser) throw new HttpError(409, 'limit reached');
      return repo.insert({ userId, url });
    },
  };
}

// A fake repository that pretends the user already has 3 bookmarks
const fullRepo = {
  findByUser: async () => [{}, {}, {}],
  insert: async () => { throw new Error('should not be called'); },
};

const service = createBookmarkService({ repo: fullRepo, maxPerUser: 3 });
service.add('ana', 'https://example.com').catch((err) => console.log(err.status, err.message));
409 limit reached

This "pass dependencies in" style is dependency injection by hand. NestJS automates exactly this pattern — you'll see it again in the NestJS section.

Conventions that help

Convention Benefit
createApp(deps) factory, listen() only in server.js testable, no global state
one router per feature, mounted in app.js the URL map is readable in one place
errors thrown as HttpError, handled centrally consistent error JSON
config read once in config.js no process.env scattered everywhere
feature.test.js next to the code tests move with the feature

Tip: Keep files small. When a router file passes ~200 lines or a service handles three unrelated things, split it. If you find yourself reinventing modules, DI and decorators on top of Express, that's the moment to consider NestJS.

Test yourself

Which layer should contain the rule 'a user may have at most 50 bookmarks'?

  1. The route handler
  2. The service
  3. The repository
  4. The error handler

What is the advantage of grouping files by feature (features/bookmarks/…)?

  1. Faster startup
  2. Everything about one feature lives together, so it's easier to find, change or remove
  3. Express requires it
  4. It avoids using routers

Why does the service receive repo as a parameter instead of importing it?

  1. To save memory
  2. So tests can pass a fake repository (dependency injection)
  3. Because require doesn't work in services
  4. To make it async