Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 43 ยท Getting Started

Project Setup and Structure

Set up an Express project the clean way: package.json with ES modules, routes, controllers and services folders, config from environment variables, and app vs server.

A one-file Express app is fine for learning, but real projects grow. Without a plan, index.js ends up with hundreds of lines mixing routes, business rules, database calls and configuration. A simple, consistent structure keeps each file small and makes testing easy.

Express does not force a layout, so this lesson suggests one that works for most APIs and websites. You can reshape it later. The code for real files is read-only here; a runnable demo at the end wires the same layers together inside a single file.

The folder layout

TEXT
my-app/
  package.json
  .env.example
  src/
    server.js          # starts listening (the only file that calls listen)
    app.js             # builds and exports the Express app
    config.js          # reads environment variables once
    routes/
      index.js         # combines all routers
      users.js         # URL definitions for /users
    controllers/
      users.js         # takes req, calls a service, sends res
    services/
      users.js         # business logic, no req/res
    middleware/
      error-handler.js
  tests/
    users.test.js

Who does what

Routes Map a URL and method to a controller.
Controllers Read the request, send the response.
Services Business rules. No req or res.
Data Database code behind the services.

Each layer knows only about the one below it.

1 / 2

The rule of thumb: routes say where, controllers translate HTTP, services hold the logic. A service function such as createUser(data) knows nothing about Express, so you can test it without starting a server and reuse it from a script or a queue worker. Controllers and Services develops this in detail.

package.json with ES modules

Set "type": "module" so that .js files use import/export. Also add scripts so everybody runs the app the same way:

JSON
{
  "name": "my-app",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "engines": { "node": ">=20" },
  "scripts": {
    "start": "node src/server.js",
    "dev": "node --watch src/server.js",
    "test": "node --test"
  },
  "dependencies": {
    "express": "^5.1.0"
  }
}

"private": true stops you from accidentally publishing the app to npm. engines documents the Node version you test with. More on these fields in package.json, and on module formats in ES modules.

Separate the app from the server

Split building the app from listening on a port. This tiny habit pays off in testing, because tests can import app and call it without opening a real port first.

JavaScript
// src/app.js
import express from 'express';
import routes from './routes/index.js';
import { errorHandler } from './middleware/error-handler.js';

export const app = express();

app.use(express.json());
app.use('/api', routes);
app.use(errorHandler);
JavaScript
// src/server.js
import { app } from './app.js';
import { config } from './config.js';

app.listen(config.port, (error) => {
  if (error) throw error;
  console.log(`Listening on port ${config.port} in ${config.env} mode`);
});

Configuration from environment variables

Settings that change between your laptop and production (port, database URL, secrets) belong in environment variables, not in code. Read them in one place and export plain values:

JavaScript
// src/config.js
export const config = {
  env: process.env.NODE_ENV ?? 'development',
  port: Number(process.env.PORT ?? 3000),
  databaseUrl: process.env.DATABASE_URL,
};

if (config.env === 'production' && !config.databaseUrl) {
  throw new Error('DATABASE_URL is required in production');
}

Failing early at startup is better than a mysterious crash on the first request. Node can load a .env file for you with node --env-file=.env src/server.js, so no extra package is needed. Commit a .env.example with the variable names and fake values, and keep the real .env out of git (add it to .gitignore). The Secrets and Config lesson covers this in depth, and Project Structure shows a non-Express take on layout.

Never commit secrets such as API keys or database passwords. If one slips into a public repository, treat it as stolen and rotate it.

A layered demo you can run

The next example reproduces the layout inside one file: a config object, a service with an in-memory list, a controller, a router-like route table and an app. In a real project each block would be its own file.

Node.js Config, service, controller, routes

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 that userService.find never touches req or res. You could test it with a plain function call, as the next example shows.

Node.js Testing a service without 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.

Habits that keep a project healthy

  • Start small. For three routes a single file is fine. Split when a file becomes hard to scan, not before.
  • Group by feature when the app gets big: src/users/ holding its routes, controller and service, instead of one folder per layer. Both styles work; pick one and stay consistent.
  • One place for config. Do not read process.env all over the code.
  • Keep app and listen apart so tests and tools can import the app.
  • Add a lock file. Commit package-lock.json so installs are reproducible.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why keep app.js and server.js separate?

    The app can be built and exercised without a real listening server, which makes tests simpler and faster.
  2. 2. Which layer should know about req and res?

    Controllers translate HTTP into service calls. Services stay free of HTTP so they are easy to test and reuse.
  3. 3. Where should secrets like database passwords live?

    Environment variables keep secrets out of source control; an example file documents what must be set.
  4. 4. What does "type":"module" in package.json do?

    It tells Node to treat .js files as ES modules.

Summary

  • Suggested layout: routes, controllers, services, middleware and a single config.
  • Set "type": "module" and add start, dev and test scripts.
  • Build the app in app.js and call listen only in server.js.
  • Read environment variables once, fail early if they are missing, and never commit secrets.
  • Services without req/res are easy to test.

Next: Routing Basics.