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
// 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 });
}
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
defaultare optional;DATABASE_URLandJWT_SECREThave none, so they are required. - Environment variables are always strings, but
PORTis declared as a number:env-schemaconverts it for you, soconfig.PORTreally is anumber. - Nothing here reads the
.envfile. Node already loaded it intoprocess.envthrough the--env-file-if-existsflag in thedevscript, andenv-schemajust validates what it finds there. - The
overridesparameter 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;
}
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);
}
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
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'))"
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
curl localhost:3000/health
# {"status":"ok"}
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'
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
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.tsstays pure and reusable (tests, scripts, workers), whileserver.tsis 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)