The App Instance

One App, Many Plugins

The App Instance

The Fastify factory returns an app instance — register plugins and routes on it, then call listen to start the server.

4 min read Level 1/5 #fastify#server#listen
What you'll learn
  • Configure logger, trustProxy, and bodyLimit
  • Use app.register to mount plugins
  • Use app.listen with host and port options

Fastify(options) creates a fresh app instance. Everything else — routes, plugins, hooks — is registered on that instance before you call listen.

Common Factory Options

import Fastify from 'fastify';

const app = Fastify({
  logger: true,
  trustProxy: true,
  bodyLimit: 1_048_576, // 1 MB
  disableRequestLogging: false,
  caseSensitive: true,
});

trustProxy: true makes request.ip honor X-Forwarded-For when you sit behind a load balancer. bodyLimit caps incoming JSON body size before Ajv even sees it.

Registering Plugins

import cors from '@fastify/cors';
import postsPlugin from './routes/posts.js';

await app.register(cors, { origin: true });
await app.register(postsPlugin, { prefix: '/api/posts' });

Each plugin is awaited so any startup error stops boot. Plugins compose — postsPlugin may register more plugins inside itself.

Listening

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

host: '0.0.0.0' is required inside Docker so the port is reachable from outside the container. app.listen returns a promise resolving to the listening URL — await it so Fastify can finish plugin loading first.

Defining Routes →