Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 39 ยท Getting Started

Project Structure and Configuration

Organize a Fastify project: separate app and server files, load validated configuration from environment variables, use fastify-cli, and keep the app testable.

A single server.js is perfect for a first demo, but real projects need structure. The most valuable habit you can build now is to separate building the app from starting the server. It costs almost nothing and makes testing, scripting and deployment far easier. This lesson shows a layout that scales from a tiny API to a large service, and how to load configuration safely.

One rule: build, then listen

Put app creation in a function that returns the instance without listening. Another file calls listen.

TEXT
my-api/
  package.json
  .env.example
  src/
    app.js          <- buildApp(options): creates and configures the app
    server.js       <- reads config, calls buildApp, calls listen
    config.js       <- reads and validates environment variables
    routes/
      health.js
      users.js
    plugins/
      db.js
      auth.js
  test/
    users.test.js

src/app.js:

JavaScript
import Fastify from 'fastify';
import health from './routes/health.js';
import users from './routes/users.js';

export function buildApp(opts = {}) {
  const app = Fastify(opts);
  app.register(health);
  app.register(users, { prefix: '/users' });
  return app;
}

src/server.js:

JavaScript
import { buildApp } from './app.js';
import { config } from './config.js';

const app = buildApp({ logger: { level: config.logLevel } });

try {
  await app.listen({ port: config.port, host: config.host });
} catch (err) {
  app.log.error(err);
  process.exit(1);
}

Why this matters: a test can import buildApp, create a fresh app per test, and call app.inject() without opening any port. Tools such as OpenAPI generators can also import the app to read its routes without starting a server.

A testable app, runnable

The stand-in lets you try the same pattern. The function buildApp below is what lives in app.js; the code after it is what a test file does.

Node.js buildApp() and inject(): no port needed

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.

Configuration from the environment

Configuration (port, database URL, secrets, log level) must live outside the code, because it differs between your laptop, the test server and production. The convention (from the Twelve-Factor App) is environment variables. Keep one module that reads them, converts types and fails fast when something is missing or wrong:

JavaScript
// src/config.js
const required = (name) => {
  const value = process.env[name];
  if (!value) throw new Error(`Missing environment variable ${name}`);
  return value;
};

export const config = {
  port: Number(process.env.PORT ?? 3000),
  host: process.env.HOST ?? '0.0.0.0',
  logLevel: process.env.LOG_LEVEL ?? 'info',
  databaseUrl: required('DATABASE_URL'),
};

Failing at startup with a clear message is much better than crashing later with undefined is not a string.

To load a .env file during development, Node 20.6+ has it built in:

Terminal
node --env-file=.env src/server.js

Commit a .env.example with fake values and keep the real .env out of Git (.gitignore). In production, set real variables in your platform instead of shipping a file.

You can try the validating loader right here. It takes the environment as a parameter, so it is easy to test:

Node.js Validate configuration and fail 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.

For larger apps the official plugin @fastify/env does this with a JSON Schema (the same schema language you will meet in chapter 3): it validates process.env, applies defaults and exposes the result as app.config. The idea is identical to the function above.

The fastify-cli alternative

The fastify-cli package can start an app from a plugin file, so you do not write server.js at all:

Terminal
npm install fastify-cli
npx fastify start -l info -p 3000 src/app.js

For this to work, app.js exports a plugin function instead of a built instance:

JavaScript
// src/app.js (fastify-cli style)
export default async function app(fastify, opts) {
  fastify.get('/', async () => ({ hello: 'world' }));
}

fastify generate creates a full project skeleton using this style, with routes/ and plugins/ folders loaded automatically by @fastify/autoload (covered in the plugin patterns lesson). Both approaches are valid. The explicit buildApp/server.js pair is easier to understand and to debug; the CLI style gives you zero-config startup, hot reload (--watch) and a consistent layout across teams. Pick one per project.

Where code lives

A common, scalable layout groups by feature rather than by file type once the app grows:

TEXT
src/
  modules/
    users/
      users.routes.js
      users.schema.js
      users.service.js
    orders/
      orders.routes.js
      ...
  plugins/        <- shared infrastructure: db, auth, config
  app.js
  server.js

Keep route files thin (parse input, call a service, shape output) and put business logic in plain functions that know nothing about Fastify. Those functions are trivial to unit test, and you can reuse them from scripts and background jobs.

Common mistakes

  • Calling listen() inside the module that tests import. The test then hangs or fails with EADDRINUSE.
  • Reading process.env all over the codebase. Centralize it in one config module.
  • Committing .env with real secrets.
  • Putting the database query code directly in route handlers. Extract it to a service function.
  • Mixing CommonJS and ES modules by accident. Set "type": "module" in package.json and use import everywhere.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why separate buildApp() from listen()?

    A separate builder lets tests, scripts and tools import the app without starting a server.
  2. 2. Where should secrets and per-environment settings live?

    Environment variables keep configuration out of code and let each environment differ.
  3. 3. What does node --env-file=.env server.js do?

    Node 20.6 and newer can load a dotenv-style file with the --env-file flag.
  4. 4. What is a good reason to validate configuration at startup?

    A missing DATABASE_URL should stop the process immediately with a readable message.

Summary

  • Separate buildApp() (create and configure) from server.js (read config and listen).
  • Load configuration from environment variables in one validated module; fail fast on errors.
  • node --env-file=.env loads local settings; commit only .env.example.
  • fastify-cli can start plugin-style apps, but an explicit server file is simpler to follow.
  • Group code by feature and keep route handlers thin.

Next: Routing Basics