A scalable backend template featuring modular architecture, automatic route loading, type-safe validation, and interactive API documentation.
This template provides a maintainable backend structure with a focus on developer experience and scalability. Key features include:
- Modular Architecture: Organize code by feature domains (
src/modules) for better separation of concerns. - Automatic Route Loading: Files ending in
.route.ts(or.route.js) are automatically loaded and registered as routes based on the file structure. - Zod Validation: First-class support for Zod schemas to validate requests and responses, automatically generating JSON schemas for Fastify.
- Swagger/OpenAPI: Interactive API documentation is automatically generated.
- Type-Safe Config: Environment variables are strictly typed and validated using
env-var. - Docker Ready: Includes production-optimized Dockerfile and docker-ignore settings.
.
├── public/ # Publicly served static assets
├── src/
│ ├── modules/ # Domain-specific modules (e.g., todos)
│ │ └── todos/ # Example module structure
│ ├── plugins/ # Global plugins (routes, swagger)
│ ├── bootstrap.ts # Global plugin registrations
│ ├── init.ts # Pre-startup initialization
│ ├── server.ts # Fastify instance and server configuration
│ └── main.ts # Application entry point
├── Dockerfile # Production Docker setup
├── package.json # Dependencies and scripts
└── tsconfig.json # TypeScript configuration
git clone https://github.com/jmrl23/fastify-template.git
cd fastify-templateyarn installyarn run start:dev- Starts the server with
tsx watchfor hot-reloading. - Swagger UI available at
http://localhost:3001/documentation(if PORT is 3001).
yarn run build
yarn run start| Script | Description |
|---|---|
yarn run start |
Start server. |
yarn run start:dev |
Start server in development mode with watch mode and inspector. |
yarn run start:prod |
Start server in production mode (NODE_ENV=production). |
yarn run build |
Compile TypeScript to JavaScript. |
yarn run test |
Run tests using Jest. |
yarn run format |
Format code with Prettier. |
yarn run lint |
Lint code with ESLint. |
Routes are defined in *.route.ts (or *.route.js) files within src/modules. The src/plugins/routes.ts plugin automatically discovers these files. The URL path is derived from the file path relative to src/modules.
Example: src/modules/todos/todos.route.ts -> /todos
Schemas are defined using Zod as *.schema.ts. These are used in route definitions to validate body, querystring, and params, and to type the request handlers.
Build and run the container:
docker build -t fastify-app .
docker run -p 3001:3001 --env-file .env fastify-appThis project is licensed under the MIT License.