# 5 Steps to Refactor a Fastify App for Testing and Growth — Liran Tal

Refactor a Fastify app with Prisma plugins, explicit startup, autoloaded route modules, JSON schemas, and tap tests that exercise requests without a listener.

Canonical: https://lirantal.com/blog/refactor-fastify-app-testing-growth

![Cover artwork for 5 Steps to Refactor a Fastify App for Testing and Growth](/_astro/refactor-fastify-app-testing-growth.Bs9d9ubn_2gsbV2.png)

A Fastify application can fit in one file for quite a while. Create a server, instantiate Prisma, add a few routes, and call `listen()`. That is a reasonable starting point. The trouble begins when importing that file also opens a database connection and starts an HTTP server, or when adding a route means editing a file that already owns half the application.

I would refactor that app around ownership: who creates the database client, which routes can access it, and what must succeed before the process accepts traffic. Fastify’s plugin system gives those decisions a home. Moving handlers into different files helps only when the resulting structure makes those relationships easier to follow.

These five steps take a small users API from a single file to an application with explicit startup, database cleanup, route modules, and tests. The examples use JavaScript ES modules, Fastify 5, and Node.js 24. For a reproducible database setup, they deliberately use Prisma 6.19 with SQLite; Prisma 7 changes client configuration and requires a different setup.

The refactor proceeds in five steps:

1.  [Separate building the app from starting the server](#1-separate-building-the-fastify-app-from-starting-the-server).
2.  [Give Prisma a plugin and a lifecycle](#2-give-prisma-a-plugin-and-a-lifecycle).
3.  [Autoload infrastructure and organize routes by feature](#3-autoload-infrastructure-and-organize-routes-by-feature).
4.  [Put request and response contracts beside the handler](#4-put-request-and-response-contracts-beside-the-handler).
5.  [Test boot failures and routes without a listener](#5-test-boot-failures-and-routes-without-a-network-listener).

## The starting point: a route, a database, and a listener

Install the example’s dependencies in a new directory. Keep its lockfile so subsequent installs use the same resolved versions:

```
npm init -y
npm pkg set type=module
npm install fastify@5 @fastify/autoload@6 fastify-plugin@5
npm install --save-exact prisma@6.19.0 @prisma/client@6.19.0
npm install --save-dev tap@21
mkdir -p prisma
```

Create `prisma/schema.prisma`:

```
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlite"
  url      = env("DATABASE_URL")
}

model User {
  id    Int    @id @default(autoincrement())
  email String @unique
  name  String?
}
```

Initialize the database and generate the client. Use the same environment variable when starting the server later. With this Prisma configuration, the relative SQLite path resolves beside the schema, so the database lives at `prisma/dev.db`.

```
export DATABASE_URL='file:./dev.db'
npx prisma migrate dev --name init
npx prisma generate
```

Here is the initial `server.js`:

```
import Fastify from 'fastify';
import { PrismaClient } from '@prisma/client';

const app = Fastify({ logger: true });
const prisma = new PrismaClient();

app.get('/api/users/:id', async (request, reply) => {
  const user = await prisma.user.findUnique({
    where: { id: Number(request.params.id) },
  });
  if (!user) return reply.code(404).send({ error: 'User not found' });
  return user;
});

await app.listen({ port: 3000 });
```

This works, but the file makes several decisions at once. It owns the Prisma client, the route, and the network listener. The handler converts arbitrary input into a number and returns the entire database record. Importing it in a test starts a real server, and the database has no shutdown hook.

Express applications often begin with a similar structure: a shared client imported by routers and a process entry point that accumulates initialization code. Fastify offers another organizing unit. A [Fastify plugin](https://github.com/fastify/fastify/blob/main/docs/Reference/Plugins.md) receives an application instance and can register routes, decorators, and lifecycle hooks in a defined scope.

That scope matters more than the directory name. Through [Fastify encapsulation](https://github.com/fastify/fastify/blob/main/docs/Reference/Encapsulation.md), child plugins inherit their parent’s decorators and hooks, while changes inside a child normally stay there. A database plugin and a route plugin registered as siblings therefore need an intentional way to share the database decorator.

## 1\. Separate building the Fastify app from starting the server

First, move construction into `app.js`. Keep the route unchanged for this step; the database ownership will move next. An async factory gives startup work an explicit place to finish before the caller receives a usable application.

```
// app.js
import Fastify from 'fastify';
import { PrismaClient } from '@prisma/client';

export default async function buildApp(options = {}) {
  const app = Fastify({ logger: true, ...options });
  const prisma = new PrismaClient();
  app.addHook('onClose', async () => prisma.$disconnect());

  app.get('/api/users/:id', async (request, reply) => {
    const user = await prisma.user.findUnique({
      where: { id: Number(request.params.id) },
    });
    if (!user) return reply.code(404).send({ error: 'User not found' });
    return user;
  });

  try {
    await app.ready();
    return app;
  } catch (error) {
    await app.close();
    throw error;
  }
}
```

`app.ready()` boots the registered plugins and waits for their initialization. It does not open a listening socket. Returning a promise is useful here because a caller can await the complete application, including any dependency checks we put in plugins, before deciding how to use it.

Replace `server.js` with the process entry point:

```
import buildApp from './app.js';

let app;
try {
  app = await buildApp();
  await app.listen({
    port: Number(process.env.PORT ?? 3000),
    host: '127.0.0.1',
  });
} catch (error) {
  console.error(error);
  if (app) await app.close();
  process.exitCode = 1;
}

for (const signal of ['SIGINT', 'SIGTERM']) {
  process.once(signal, async () => {
    try {
      await app?.close();
    } catch (error) {
      console.error(error);
      process.exitCode = 1;
    }
  });
}
```

The application instance now belongs to its caller. Tests can create one instance per test, and the process entry point owns signals and the listening address. Use `0.0.0.0` when your container or deployment requires an externally reachable listener; the local example binds to loopback deliberately. In production, also give shutdown a deadline that fits the platform’s termination window.

Quick check: `node --input-type=module -e "import buildApp from './app.js'; const app = await buildApp({ logger: false }); await app.close();"` should exit without opening port 3000. This is the first useful boundary: construction has become independently callable.

## 2\. Give Prisma a plugin and a lifecycle

A Prisma client should live for the application instance, rather than being constructed inside a request handler. Creating a client for every request repeats initialization and can multiply connection pools with databases such as PostgreSQL. Putting a client at module scope creates a different problem: tests and multiple application instances share ownership implicitly.

Create `plugins/prisma.js`:

```
import fp from 'fastify-plugin';
import { PrismaClient } from '@prisma/client';

async function prismaPlugin(app, options) {
  const prisma = options.prisma ?? new PrismaClient();
  const ownsClient = options.prisma === undefined;

  app.decorate('prisma', prisma);
  if (ownsClient) {
    app.addHook('onClose', async () => prisma.$disconnect());
  }
  await prisma.$connect();
}

export default fp(prismaPlugin, { name: 'prisma' });
```

The [`fastify-plugin` wrapper](https://github.com/fastify/fastify-plugin) deliberately exposes this decorator to the containing scope. Routes registered afterward in that scope can access `app.prisma`. Without the wrapper, an ordinary sibling route plugin would not inherit a decorator created inside the database plugin.

The plugin connects during boot, so an initial connection failure rejects `buildApp()` before `listen()` runs. Registering cleanup before connecting also gives the factory’s failure path a chance to release the client. A successful connection verifies connectivity; it does not prove that migrations are current or that every query will succeed. Run migrations as a deployment step and handle request-time failures separately.

The optional injected client makes ownership explicit. The plugin connects it, but only disconnects clients it created itself. A test or another caller that provides a client remains responsible for that client’s cleanup. This avoids one test unexpectedly disconnecting a resource another test owns.

For the intermediate version of `app.js`, import the plugin, register it before the route, remove the local `PrismaClient` construction and close hook, and change the query to `app.prisma.user.findUnique(...)`:

```
import prismaPlugin from './plugins/prisma.js';

// Inside buildApp(), before registering routes:
app.register(prismaPlugin);
```

Keep the `ready()` and cleanup block from step 1. Quick check: start `node server.js` with `DATABASE_URL` unset in a separate shell. Startup should fail instead of accepting traffic and discovering the missing configuration on the first users request. Restore `DATABASE_URL` before continuing.

## 3\. Autoload infrastructure and organize routes by feature

Once the application has several infrastructure plugins, maintaining their import list becomes repetitive. [`@fastify/autoload`](https://github.com/fastify/fastify-autoload) registers plugins from a directory. It is a convenience for composition, and it still follows Fastify’s boot and encapsulation rules. File discovery does not remove dependency ordering.

Use two loading phases: infrastructure first, then routes. Replace `app.js` with this final factory:

```
import Fastify from 'fastify';
import AutoLoad from '@fastify/autoload';
import { fileURLToPath } from 'node:url';

export default async function buildApp({ prisma, ...options } = {}) {
  const app = Fastify({ logger: true, ...options });

  app.register(AutoLoad, {
    dir: fileURLToPath(new URL('./plugins', import.meta.url)),
    options: { prisma },
  });
  app.register(AutoLoad, {
    dir: fileURLToPath(new URL('./routes', import.meta.url)),
    dirNameRoutePrefix: false,
    options: { prefix: '/api' },
  });

  try {
    await app.ready();
    return app;
  } catch (error) {
    await app.close();
    throw error;
  }
}
```

Move the users route into `routes/users/index.js`. Before adding validation, its contents are:

```
export default async function userRoutes(app) {
  app.get('/:id', async (request, reply) => {
    const user = await app.prisma.user.findUnique({
      where: { id: Number(request.params.id) },
    });
    if (!user) return reply.code(404).send({ error: 'User not found' });
    return user;
  });
}

export const autoPrefix = '/users';
```

The loader supplies `/api`; this module supplies `/users`; the handler supplies `/:id`. The resulting URL is `/api/users/:id`. Setting `dirNameRoutePrefix: false` disables directory-derived prefixes so the explicit `autoPrefix` controls the feature path. Otherwise, directory names also participate in route naming, which can make a later file move change a public URL.

This is a small vertical module: the users routes live together, and products can have a separate `routes/products/index.js` with `autoPrefix = '/products'`. As the feature grows, keep its schemas and business logic nearby. Put files that are not plugins outside autoloaded directories, or configure `ignorePattern`; autoload should not try to register a schema object as a plugin.

An explicit registration remains a good choice for a small application:

```
app.register(userRoutes, { prefix: '/api/users' });
app.register(productRoutes, { prefix: '/api/products' });
```

Choose this approach instead of autoload when seeing the complete registration list is more useful than automatic discovery. With explicit registration, the loader-specific `autoPrefix` export has no effect. Keep ordinary route modules encapsulated: wrapping them in `fastify-plugin` changes how registration options such as prefixes behave.

Quick check: after `const app = await buildApp()`, print `app.printRoutes()` and then close the app. Confirm that the tree contains `/api/users/:id` and that `/users/:id` returns 404. Check effective URLs rather than inferring them from the folder tree.

## 4\. Put request and response contracts beside the handler

The route currently accepts any string as an ID and asks JavaScript to turn it into a number. Values such as `hello` become `NaN`, which pushes a request validation problem into the database layer. The response also exposes whatever fields the Prisma model returns, making future model changes affect the API accidentally.

Replace `routes/users/index.js` with a route that declares both boundaries:

```
export default async function userRoutes(app) {
  app.get('/:id', {
    schema: {
      params: {
        type: 'object',
        required: ['id'],
        properties: { id: { type: 'integer', minimum: 1 } },
      },
      response: {
        200: {
          type: 'object',
          required: ['id', 'name'],
          properties: {
            id: { type: 'integer' },
            name: { type: 'string', nullable: true },
          },
        },
        404: {
          type: 'object',
          required: ['error'],
          properties: { error: { type: 'string' } },
        },
      },
    },
  }, async (request, reply) => {
    const user = await app.prisma.user.findUnique({
      where: { id: request.params.id },
      select: { id: true, name: true },
    });
    if (!user) return reply.code(404).send({ error: 'User not found' });
    return user;
  });
}

export const autoPrefix = '/users';
```

Fastify’s default Ajv configuration coerces a valid numeric path parameter into an integer. The handler therefore receives `request.params.id` as a number. Invalid IDs fail validation with HTTP 400 before the query runs. Fastify 5 expects full JSON schemas for these objects; the `type` and `properties` declarations are part of the contract.

[Fastify validation and serialization](https://github.com/fastify/fastify/blob/main/docs/Reference/Validation-and-Serialization.md) are separate mechanisms. The request schema validates incoming data. The response schema controls serialization, including which declared properties appear in the response; it is not a general database integrity check. The Prisma `select` also limits the data fetched, so this endpoint does not retrieve or serialize email addresses.

Schemas cannot decide whether a caller may read a particular user. Add authentication and resource authorization in appropriate hooks, and keep database lookups out of initial schema validation. Treat schema definitions as trusted application code, since Fastify compiles them into functions. Never accept a schema supplied by an untrusted API caller and pass it to the compiler.

Quick check: `curl -i http://127.0.0.1:3000/api/users/hello` should return 400, while a valid ID with no matching row should return the explicit 404 response. A database outage should remain a server error, rather than being disguised as a missing user.

## 5\. Test boot failures and routes without a network listener

The factory now gives tests the same composition path as the process entry point. [Fastify’s testing guide](https://github.com/fastify/fastify/blob/main/docs/Guides/Testing.md) documents `inject()`, which exercises HTTP request handling without opening a port. Use it to check status codes, validation behavior, and response bodies. Awaiting the factory also makes plugin boot errors observable in tests.

Create `test/users.test.js`:

```
import t from 'tap';
import buildApp from '../app.js';

const queries = [];
const prisma = {
  $connect: async () => {},
  user: {
    findUnique: async (query) => {
      queries.push(query);
      return query.where.id === 1
        ? { id: 1, name: 'Ada', email: 'private@example.com' }
        : null;
    },
  },
};

const app = await buildApp({ logger: false, prisma });
t.teardown(() => app.close());

const found = await app.inject('/api/users/1');
t.equal(found.statusCode, 200);
t.same(found.json(), { id: 1, name: 'Ada' });
t.same(queries[0], {
  where: { id: 1 }, select: { id: true, name: true },
});

const count = queries.length;
t.equal((await app.inject('/api/users/hello')).statusCode, 400);
t.equal(queries.length, count);
t.equal((await app.inject('/api/users/999')).statusCode, 404);
t.equal((await app.inject('/users/1')).statusCode, 404);

await t.rejects(buildApp({
  logger: false,
  prisma: { $connect: async () => { throw new Error('DB unavailable'); } },
}), /DB unavailable/);
```

Run `npx tap --disable-coverage test/users.test.js`. This suite checks successful serialization, integer coercion, rejection before database access, a missing record, prefix behavior, and startup failure. Coverage is disabled for this small example so a coverage threshold does not obscure the behavior under test; use an appropriate coverage policy in your application.

The fake intentionally returns an email field, even though the real query selects only public fields. That tests the response serialization boundary independently of the query. The query assertion checks the database boundary too. A separate integration suite should use a temporary database to verify migrations, real Prisma queries, and cleanup; a fake cannot establish those properties.

There is another boot failure worth preserving as a regression test. Two plugins registering the same method and URL, with the same routing constraints, cause Fastify to reject startup:

```
import Fastify from 'fastify';
import t from 'tap';

const duplicate = Fastify();
duplicate.register(async (app) => {
  app.get('/collision', async () => ({ source: 'first' }));
});
duplicate.register(async (app) => {
  app.get('/collision', async () => ({ source: 'second' }));
});
await t.rejects(duplicate.ready(), { code: 'FST_ERR_DUPLICATED_ROUTE' });
await duplicate.close();
```

Plugin encapsulation does not create separate URL namespaces. Prefixes and routing constraints determine whether routes collide. Express behaves differently: matching handlers run in registration order, and an earlier handler that ends the response can shadow a later one. Fastify’s duplicate-route error catches this particular wiring mistake during boot, before a request reaches the application.

## What these boundaries cost, and what they leave to you

The final layout has a process entry point, an application factory, a database plugin, and a feature route. That is more machinery than the original file, so each boundary should earn its place. Autoload adds conventions to learn; explicit imports are easier to navigate when there are only two or three plugins. A shared database decorator is convenient, but feature-local resources should stay inside their feature’s scope.

Decision

Useful when

Cost or limitation

Explicit plugin registration

The composition list is short or ordering needs close review

Each new plugin requires an import and registration

Autoload in two phases

Infrastructure and feature modules keep growing

File layout becomes part of application configuration

Fake Prisma client

You need fast route and boot behavior checks

It cannot verify SQL, migrations, or connection cleanup

Temporary real database

You need confidence in persistence behavior

Setup and isolation take more work

Fastify already uses Pino when logging is enabled. Configure [Fastify logging](https://github.com/fastify/fastify/blob/main/docs/Reference/Logging.md) deliberately, including redaction for authorization headers and cookies, and decide which request details are safe to record. Avoid logging entire request bodies by default. For distributed tracing, initialize instrumentation before importing the libraries it needs to instrument, and check that the deployed application exports useful spans.

Authentication needs a similar ownership decision. Register shared authentication infrastructure where features can inherit it, then put authorization hooks around the routes they protect. An authentication decorator does not protect anything until a hook or handler calls it. Check that a users hook does not accidentally cover public health endpoints, and test both permitted and denied requests.

Connecting before startup gives you one dependency check at one moment. A running database can still become unavailable later. Keep liveness separate from readiness, define whether database availability should remove an instance from service, and set timeouts so a health check cannot hang indefinitely. These decisions depend on deployment behavior; they do not follow automatically from making `buildApp()` async.

## Questions that come up during the refactor

### Does every plugin need `fastify-plugin`?

No. The Prisma plugin uses it because sibling routes need its decorator. Ordinary route plugins benefit from encapsulation, especially when hooks apply to one feature. Use the wrapper when sharing scope is an intentional part of the plugin’s contract.

### Does autoload guarantee dependency order?

Autoload participates in Fastify’s plugin boot process, but a directory of files is not a dependency graph. This example registers the infrastructure loader before the routes loader. If infrastructure plugins depend on each other, register them explicitly in the required order or use autoload’s dependency metadata support, then test the boot path.

### Will this refactor make requests faster?

Moving a handler between files does not establish a throughput improvement. Reusing a Prisma client avoids per-request client creation, and compiled response schemas can affect serialization, but database latency may dominate the request. Compare the same endpoint, dataset, concurrency, and logging configuration before claiming a performance gain; record latency percentiles and errors as well as requests per second.

## Apply the refactor one boundary at a time

Start by extracting the factory and making the existing route testable through `inject()`. Move the database into a plugin once its lifecycle is explicit. Choose manual registration or autoload based on the composition you actually have, then add request and response schemas to the routes you expose. Preserve tests for boot failure, invalid input, and duplicate routes as the application grows.

The useful result is an application whose behavior you can explain before starting its listener: the database initializes, routes inherit the resources they need, conflicting registrations fail, and tests exercise that same setup. A folder tree is helpful when it makes those facts visible.

You can find my related Node.js work on [GitHub](https://github.com/lirantal) and follow [@liran\_tal on X](https://x.com/liran_tal) for more guides.

## More writing

[All writing](/blog)

*   Nov 14, 2026

    ### [Every Security Weakness Matters When Vulnerability Chaining is King](/blog/every-security-weakness-matters-vulnerability-chaining)

*   Sep 5, 2026

    ### [Self-Hosting Hermes Agent with Matrix E2EE on Proxmox](/blog/self-host-hermes-agent-matrix-e2ee-proxmox)

*   Aug 2, 2026

    ### [The Practical Second Brain: Building an LLM-Operated Markdown Knowledge Graph](/blog/practical-second-brain-llm-markdown-knowledge-graph)


* * *

Liran Tal is the author of the book [Node.js Secure Coding: Defending Against Command Injection Vulnerabilities](https://www.nodejs-security.com/)

[Start Building Secure Node.js Applications](https://www.nodejs-security.com/)

 [![](/_astro/nodejs-secure-coding-book-3d-style.DiTWpzFs_Z3c7s1.png)](https://www.nodejs-security.com/)
