# A Fastify 5 service skeleton

Verified 2026-09 against <https://fastify.dev/docs/latest/>, <https://zod.dev/> and
<https://nodejs.org/api/cli.html>. Fastify 5 requires Node 20 or newer; this skeleton targets Node 24.

## 1. `package.json`

```json
{
  "name": "orders-api",
  "type": "module",
  "engines": { "node": ">=24" },
  "scripts": {
    "dev": "tsx watch src/server.ts",
    "build": "tsc -p tsconfig.json",
    "start": "node dist/server.js",
    "typecheck": "tsc --noEmit",
    "test": "vitest run"
  }
}
```

`"type": "module"` is the decision everything else follows from. With `module: "NodeNext"` in
`tsconfig.json`, relative imports keep the `.js` extension in source — `import { config } from
'./config.js'` — even though the file on disk is `config.ts`.

## 2. `src/app.ts` — builds the app, never listens

```ts
import Fastify, { type FastifyInstance } from 'fastify';
import { config } from './config.js';
import { errorHandler } from './errors.js';
import { orderRoutes } from './modules/orders/routes.js';

export function buildApp(): FastifyInstance {
  const app = Fastify({
    logger: {
      level: config.LOG_LEVEL,
      redact: ['req.headers.authorization', 'req.headers.cookie', '*.password'],
    },
    requestIdHeader: 'x-request-id',
    bodyLimit: 1_048_576,
  });

  app.setErrorHandler(errorHandler);
  app.register(orderRoutes, { prefix: '/orders' });

  return app;
}
```

Returning the instance instead of listening is what lets `nodejs-testing` call `app.inject()` with no
socket, no port and no race.

## 3. `src/server.ts` — the only file that listens

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

const app = buildApp();

try {
  await app.listen({ port: config.PORT, host: '0.0.0.0' });
} catch (error) {
  app.log.fatal({ error }, 'failed to start');
  process.exit(1);
}

process.on('unhandledRejection', (error) => {
  app.log.fatal({ error }, 'unhandled rejection');
  process.exit(1);
});
```

`host: '0.0.0.0'` matters in a container: the default binds to localhost only and the service looks
dead to everything outside the container.

Signal handling and draining belong to `service-operability`, which owns that sequence for both
stacks — do not write a second version of it here.

## 4. `src/errors.ts` — typed errors and one handler

```ts
import type { FastifyError, FastifyReply, FastifyRequest } from 'fastify';
import { ZodError } from 'zod';

export class AppError extends Error {
  constructor(
    readonly status: number,
    readonly type: string,
    readonly title: string,
    readonly detail?: string,
  ) {
    super(title);
    this.name = new.target.name;
  }
}

export class NotFoundError extends AppError {
  constructor(what: string) {
    super(404, 'https://errors.example.com/not-found', `${what} was not found`);
  }
}

export class ConflictError extends AppError {
  constructor(detail: string) {
    super(409, 'https://errors.example.com/conflict', 'Request conflicts with current state', detail);
  }
}

export function errorHandler(
  error: FastifyError | Error,
  request: FastifyRequest,
  reply: FastifyReply,
): void {
  if (error instanceof ZodError) {
    reply.status(400).type('application/problem+json').send({
      type: 'https://errors.example.com/validation',
      title: 'Request validation failed',
      status: 400,
      instance: request.url,
      errors: error.issues.map((i) => ({ path: i.path.join('.'), message: i.message })),
    });
    return;
  }

  if (error instanceof AppError) {
    reply.status(error.status).type('application/problem+json').send({
      type: error.type,
      title: error.title,
      status: error.status,
      detail: error.detail,
      instance: request.url,
    });
    return;
  }

  // Unknown: a bug. Log everything, tell the client nothing.
  request.log.error({ err: error }, 'unhandled error');
  reply.status(500).type('application/problem+json').send({
    type: 'about:blank',
    title: 'Internal Server Error',
    status: 500,
    instance: request.url,
  });
}
```

The last branch is the one that matters: the default for an unrecognised error is an empty 500, so a
new error type added next year cannot start leaking internals by omission.

## 5. A route module

```ts
import type { FastifyInstance } from 'fastify';
import { z } from 'zod';
import { NotFoundError } from '../../errors.js';
import * as orders from './service.js';

const CreateOrder = z.object({
  sku: z.string().min(1),
  qty: z.number().int().positive().max(100),
});

const OrderId = z.object({ id: z.uuid() });

export async function orderRoutes(app: FastifyInstance): Promise<void> {
  app.post('/', async (request, reply) => {
    const input = CreateOrder.parse(request.body);
    const order = await orders.create(input);
    return reply.status(201).header('location', `/orders/${order.id}`).send(order);
  });

  app.get('/:id', async (request) => {
    const { id } = OrderId.parse(request.params);
    const order = await orders.findById(id);
    if (!order) {
      throw new NotFoundError('Order');
    }
    return order;
  });
}
```

A Fastify plugin is an `async` function taking the instance; registering it with a `prefix` keeps the
route paths relative. Everything the route does is parse, call one service function, shape the
response — business rules live in `service.ts` where a test can reach them without HTTP.

## 6. Production Dockerfile

```dockerfile
FROM node:24-slim AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev

FROM node:24-slim
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist
COPY --from=build /app/package.json ./
USER node
CMD ["node", "dist/server.js"]
```

Three details that are easy to get wrong: `npm ci` (not `install`) so the lockfile is authoritative;
`USER node` so the process is not root; and `CMD ["node", …]` in exec form with no shell wrapper, so
the process is PID 1 and actually receives `SIGTERM`. An `npm start` CMD puts npm at PID 1 and the
signal never reaches your handler.
