DEV Community

Cover image for Your first server (app.ts, server.ts, config.ts) — Fastify with TypeScript (part 4/18)
Antonio Tripodi
Antonio Tripodi

Posted on Edited on

Your first server (app.ts, server.ts, config.ts) — Fastify with TypeScript (part 4/18)

Your first server (app.ts, server.ts, config.ts)

Fourth chapter of the "Fastify with TypeScript" series. Let's build our first server following a widely-used convention from the start: the app build step (app.ts) is separated from the server startup step (server.ts), and configuration comes from environment variables validated against a schema (config.ts).

We continue in the my-fastify-app project from the previous chapter. The three files below replace the temporary src/server.ts we used to test the setup.


config.ts — typed configuration

Almost every later chapter needs a value from the environment: a database URL, a JWT secret, a port. Reading process.env.X directly gives you string | undefined everywhere and fails silently when a variable is missing. env-schema validates the environment once at startup and gives you a fully typed object.

npm install env-schema typebox
Enter fullscreen mode Exit fullscreen mode
// src/config.ts
import envSchema from 'env-schema';
import { Type, type Static } from 'typebox';

const ConfigSchema = Type.Object({
  PORT: Type.Number({ default: 3000 }),
  LOG_LEVEL: Type.String({ default: 'info' }),
  DATABASE_URL: Type.String(),
  JWT_SECRET: Type.String({ minLength: 32 }),
  CORS_ORIGIN: Type.String({ default: 'http://localhost:5173' }),
});

export type Config = Static<typeof ConfigSchema>;

export function loadConfig(overrides: Partial<Config> = {}): Config {
  return envSchema<Config>({ schema: ConfigSchema, data: overrides });
}
Enter fullscreen mode Exit fullscreen mode

This is our first contact with TypeBox: Type.Object({...}) builds a JSON Schema, and Static<typeof ConfigSchema> derives the matching TypeScript type from it, so the schema and the type can never disagree. We'll use the same idea for request validation in chapter 7.

A few things to notice:

  • Variables with a default are optional; DATABASE_URL and JWT_SECRET have none, so they are required.
  • Environment variables are always strings, but PORT is declared as a number: env-schema converts it for you, so config.PORT really is a number.
  • Nothing here reads the .env file. Node already loaded it into process.env through the --env-file-if-exists flag in the dev script, and env-schema just validates what it finds there.
  • The overrides parameter lets tests inject their own values. They take precedence over the environment, so a test never picks up your development database by accident.

app.ts — building the instance

// src/app.ts
import Fastify, { type FastifyServerOptions } from 'fastify';
import { loadConfig, type Config } from './config.ts';

declare module 'fastify' {
  interface FastifyInstance {
    config: Config;
  }
}

export type App = ReturnType<typeof buildApp>;

export function buildApp(opts: FastifyServerOptions = {}, configOverrides: Partial<Config> = {}) {
  const config = loadConfig(configOverrides);

  const app = Fastify({
    logger: { level: config.LOG_LEVEL },
    ...opts,
  });

  app.decorate('config', config);

  app.get('/health', async () => ({ status: 'ok' }));

  // you'll register plugins, hooks and routes here in the next chapters
  // app.register(import('./plugins/database.ts'));
  // app.register(import('./users/users.route.ts'), { prefix: '/api/v1/users' });

  return app;
}
Enter fullscreen mode Exit fullscreen mode

Two details worth noticing: app.decorate('config', config) makes the configuration available as fastify.config inside every plugin (the declare module block tells TypeScript about it — more on this in the decorators chapter), and the exported App type lets tests and scripts refer to the exact instance type without spelling out its generics.

Notice also what buildApp() does not do: it never calls listen(). It only builds and returns the instance.

server.ts — entry point

// src/server.ts
import { buildApp } from './app.ts';

const app = buildApp();

try {
  await app.listen({ port: app.config.PORT, host: '0.0.0.0' });
} catch (err) {
  app.log.error(err);
  process.exit(1);
}
Enter fullscreen mode Exit fullscreen mode

Top-level await is available because the project is an ES module ("type": "module"). host: '0.0.0.0' makes the server reachable from outside the machine, which is what you need inside a Docker container (chapter 18); without it Fastify only listens on localhost.

Run it

Open the .env file from the previous chapter and add the two required variables:

# .env
PORT=3000
DATABASE_URL=postgres://postgres:postgres@localhost:5432/app
JWT_SECRET=paste-here-the-value-generated-below
Enter fullscreen mode Exit fullscreen mode

JWT_SECRET must be at least 32 characters long. Generate a random one with:

node -e "console.log(require('node:crypto').randomBytes(32).toString('hex'))"
Enter fullscreen mode Exit fullscreen mode

You don't need a database yet: nothing connects to DATABASE_URL until chapter 13, the configuration only checks that the variable is there.

npm run dev
Enter fullscreen mode Exit fullscreen mode
curl localhost:3000/health
# {"status":"ok"}
Enter fullscreen mode Exit fullscreen mode

In the terminal where the server runs you'll see the JSON log lines written by Fastify's logger, starting with Server listening at http://127.0.0.1:3000.

See the validation at work

Stop the server, comment out the JWT_SECRET line in .env and start it again. The process refuses to start:

Error: env must have required property 'JWT_SECRET'
Enter fullscreen mode Exit fullscreen mode

Put the variable back with a value that is too short, such as JWT_SECRET=short:

Error: env/JWT_SECRET must NOT have fewer than 32 characters
Enter fullscreen mode Exit fullscreen mode

That is much better than discovering the problem on the first request that needs the secret. Restore the real value before going on.

With this structure, app.ts stays pure and reusable (tests, scripts, workers), while server.ts is the only place where the application actually "connects" to the outside world: TCP port, shutdown signals, process exit codes.


⬅️ Previous chapter: Project setup · ➡️ Next chapter: Routing and request handling

This article is part of the "Fastify with TypeScript" series — chapter 4 of 18.

Top comments (0)