Lesson 17 / 32
Project Structure with autoload
Organize a Fastify app into plugins and routes folders and load them automatically with @fastify/autoload.
Folders as plugins
Put shared plugins in plugins/ and route modules in routes/, then let autoload register them.
// src/app.js
import AutoLoad from '@fastify/autoload';
import { join } from 'node:path';
export default async function app(fastify, opts) {
fastify.register(AutoLoad, { dir: join(import.meta.dirname, 'plugins') });
fastify.register(AutoLoad, { dir: join(import.meta.dirname, 'routes'), options: { prefix: '/api' } });
}Export build() from app.js and call listen only in server.js. Tests can then import the app and use inject without opening a port.