Skip to content

flaviodelgrosso/fastify-forge

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

⚑ Fastify Forge ⚑

downloads npm license CI

Fastify Forge empowers developers to build lightning-fast, enterprise-grade REST APIs with zero configuration overhead. Powered by Fastify, the best framework in the town for Node.js, TypeScript and battle-tested plugins, this isn't just another boilerplateβ€”it's your secret weapon for backend development.

Quick Navigation: πŸš€ Quick Start β€’ πŸ“– Features β€’ πŸ› οΈ Development Guide β€’ 🎯 Examples

Table of Contents


⚑ Why Use Fastify Forge?

"From idea to production in under 5 minutes" - That's the Fastify Forge promise.

🎯 Built for Modern Development

  • πŸ”₯ Performance First: Fastify is the fastest Node.js frameworks
  • πŸ›‘οΈ Enterprise Security: Built-in CORS, Helmet, Rate Limiting, and Authentication
  • πŸ“Š Type Safety: Full TypeScript support with runtime validation using TypeBox
  • πŸ“š Auto Documentation: Swagger/OpenAPI docs generated automatically
  • βš™οΈ Zero Config: Works out of the box, customize when you need to
  • 🐳 Docker Ready: Production-ready containerization included

🌟 Perfect For

  • Startups building MVPs that need to scale
  • Enterprise teams requiring robust, maintainable APIs
  • Full-stack developers who want backend peace of mind
  • DevOps engineers seeking deployment simplicity

πŸš€ Quick Start

⚑ One-Command Setup

Create a new project in seconds:

npx fastify-forge@latest
cd my-api

πŸƒβ€β™‚οΈ Start Developing

# Install dependencies
pnpm install

# Start the development server with hot-reload
pnpm dev

That's it! Your API is now running at http://localhost:3000

πŸŽ‰ What You Get Instantly

  • βœ… API Documentation: Visit http://localhost:3000/documentation
  • βœ… Health Check: GET /health endpoint ready to use
  • βœ… Type Safety: Full TypeScript support with auto-completion
  • βœ… Authentication: Auth system ready to configure
  • βœ… Database: PostgreSQL integration with Drizzle ORM

πŸ” Test Your First Endpoint

curl http://localhost:3000/health
# Response: {"status":"ok"}

πŸ› οΈ What Makes Fastify Forge Special

πŸ›‘οΈ Enterprise Security

// Built-in security headers, CORS, and rate limiting
// Zero configuration required!
app.register(helmet);
app.register(cors);
app.register(rateLimit, {
  max: 100,
  timeWindow: '1 minute'
});

πŸ“Š Type-Safe Development

// Define your API with full type safety
const UserSchema = Type.Object({
  id: Type.String(),
  email: Type.String({ format: 'email' }),
  name: Type.String({ minLength: 1 })
});

app.post('/users', {
  schema: {
    body: UserSchema,
    response: {
      201: UserSchema
    }
  }
}, async (request, reply) => {
  // request.body is fully typed!
  const user = await createUser(request.body);
  return reply.code(201).send(user);
});

πŸ“š Auto-Generated Documentation

API Documentation

Beautiful, interactive API documentation generated automatically from your TypeScript schemas

πŸ”§ Developer Experience

  • Hot Reload: Instant development feedback
  • ESLint + Prettier: Code quality enforced
  • Husky: Pre-commit hooks for consistency
  • Jest: Comprehensive testing setup
  • PM2: Production process management

πŸ“– Development Guide

πŸ—οΈ Project Structure

fastify-forge/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ app.ts              # Application setup & plugins
β”‚   β”œβ”€β”€ server.ts           # Server entry point
β”‚   β”œβ”€β”€ auth.ts             # Authentication logic
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   └── env.config.ts   # Environment configuration
β”‚   β”œβ”€β”€ db/
β”‚   β”‚   β”œβ”€β”€ index.ts        # Database connection
β”‚   β”‚   └── schema.ts       # Database schema
β”‚   β”œβ”€β”€ plugins/
β”‚   β”‚   β”œβ”€β”€ external/       # Third-party plugins
β”‚   β”‚   └── internal/       # Custom plugins
β”‚   └── routes/
β”‚       β”œβ”€β”€ health.ts       # Health check endpoint
β”‚       └── api/v1/         # Versioned API routes
β”œβ”€β”€ test/                   # Test files
β”œβ”€β”€ docker-compose.yml      # Docker setup
└── process.yml             # PM2 configuration

πŸ”§ Environment Setup

  1. Copy the environment template:

    cp .env.example .env
  2. Configure your environment variables:

    # Database
    POSTGRES_HOST=localhost
    POSTGRES_USER=your_user
    POSTGRES_PASSWORD=your_password
    POSTGRES_DB=your_database
    POSTGRES_PORT=5432
    
    # Server
    HOST=localhost
    PORT=3000
    NODE_ENV=development
    LOG_LEVEL=info
  3. Validate configuration:

    pnpm dev
    # βœ… Configuration validated automatically on startup

πŸ›£οΈ Adding New Routes

Create a new route file in src/routes/:

import type { FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox';
import { Type } from '@sinclair/typebox';

const UserSchema = Type.Object({
  id: Type.String(),
  name: Type.String(),
  email: Type.String({ format: 'email' })
});

const usersRoute: FastifyPluginAsyncTypebox = async (app) => {
  app.route({
    url: '/users',
    method: 'GET',
    schema: {
      tags: ['Users'],
      response: {
        200: Type.Array(UserSchema)
      }
    },
    handler: async () => {
      return [
        { id: '1', name: 'John Doe', email: '[email protected]' }
      ];
    }
  });
};

export default usersRoute;

πŸ”Œ Creating Custom Plugins

Add custom functionality in src/plugins/internal/:

import type { FastifyPluginAsync } from 'fastify';
import fp from 'fastify-plugin';

const myPlugin: FastifyPluginAsync = async (app) => {
  app.decorate('myUtility', () => {
    return 'Hello from my plugin!';
  });
};

export default fp(myPlugin);

πŸ—ƒοΈ Database Operations

Using Drizzle ORM for type-safe database operations:

import { eq } from 'drizzle-orm';
import { users } from '../db/schema.js';

// In your route handler
const getUsers = async () => {
  return await app.db.select().from(users);
};

const getUserById = async (id: string) => {
  return await app.db.select().from(users).where(eq(users.id, id));
};

🎯 Real-World Examples

πŸ” Protected Route with Authentication

const protectedRoute: FastifyPluginAsyncTypebox = async (app) => {
  // Apply authentication hook to all routes in this plugin
  app.addHook('preHandler', app.authenticate);
  
  app.route({
    url: '/profile',
    method: 'GET',
    schema: {
      tags: ['User'],
      security: [{ bearerAuth: [] }]
    },
    handler: async (request) => {
      // request.user is available after authentication
      return { user: request.user };
    }
  });
};

πŸ“€ File Upload Endpoint

const uploadRoute: FastifyPluginAsyncTypebox = async (app) => {
  app.route({
    url: '/upload',
    method: 'POST',
    schema: {
      tags: ['Files'],
      consumes: ['multipart/form-data']
    },
    handler: async (request, reply) => {
      const data = await request.file();
      
      if (!data) {
        return reply.badRequest('No file uploaded');
      }
      
      // Process the file...
      return { filename: data.filename, size: data.file.readableLength };
    }
  });
};

πŸ” Database Integration Example

const postsRoute: FastifyPluginAsyncTypebox = async (app) => {
  app.route({
    url: '/posts',
    method: 'POST',
    schema: {
      tags: ['Posts'],
      body: Type.Object({
        title: Type.String({ minLength: 1 }),
        content: Type.String({ minLength: 1 })
      }),
      response: {
        201: Type.Object({
          id: Type.String(),
          title: Type.String(),
          content: Type.String(),
          createdAt: Type.String()
        })
      }
    },
    handler: async (request, reply) => {
      const { title, content } = request.body;
      
      const [post] = await app.db.insert(posts).values({
        title,
        content,
        authorId: request.user.id
      }).returning();
      
      return reply.code(201).send(post);
    }
  });
};

🚒 Production Deployment

🐳 Docker Deployment

# Build the image
docker build -t my-api .

# Run with docker-compose
docker-compose up -d

⚑ PM2 Deployment

# Build for production
pnpm build

# Start with PM2
pnpm pm2

# Monitor processes
pm2 monit

☁️ Cloud Deployment

Vercel/Netlify:

pnpm build
# Deploy the `dist` folder

AWS/GCP/Azure:

  • Use the included Dockerfile
  • Set environment variables
  • Configure health checks on /health

πŸ” Production Checklist

  • Environment variables configured
  • Database migrations run
  • SSL/TLS certificates in place
  • Rate limiting configured
  • Monitoring and logging set up
  • Health checks responding
  • Load balancer configured (if needed)

πŸ§ͺ Testing & Quality Assurance

πŸš€ Running Tests

# Run all tests
pnpm test

# Run tests with coverage report
pnpm test:lcov

# Run linting
pnpm lint

πŸ“Š Test Coverage

Fastify Forge aims for 100% test coverage. The test setup includes:

  • Unit Tests: Individual function testing
  • Integration Tests: Route and plugin testing
  • E2E Tests: Full application flow testing

🧹 Code Quality Tools

  • ESLint: Catch code issues early powered by Neostandard
  • Husky: Pre-commit hooks
  • Commitlint: Conventional commit messages

πŸ”§ Advanced Configuration

πŸŽ›οΈ Custom Environment Variables

Extend src/config/env.config.ts:

const schema = Type.Object({
  // Existing variables...
  REDIS_URL: Type.String(),
  SMTP_HOST: Type.String(),
  JWT_SECRET: Type.String({ minLength: 32 }),
  API_RATE_LIMIT: Type.Number({ default: 100 })
});

πŸ”Œ Plugin Customization

Modify plugin settings in src/app.ts:

// Custom rate limiting
await app.register(rateLimit, {
  max: env.API_RATE_LIMIT,
  timeWindow: '1 minute',
  keyGenerator: (request) => request.ip
});

πŸ“Š Logging Configuration

const server = Fastify({
  logger: {
    level: env.LOG_LEVEL,
    transport: env.NODE_ENV === 'development' ? {
      target: 'pino-pretty',
      options: { colorize: true }
    } : undefined
  }
});

🀝 Contributing

We welcome contributions! Here's how you can help:

πŸ› Bug Reports

  1. Check existing issues first
  2. Provide detailed reproduction steps
  3. Include environment information

πŸ’‘ Feature Requests

  1. Open an issue with the enhancement label
  2. Describe the use case and benefits
  3. Consider implementation approaches

πŸ”§ Pull Requests

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Commit changes: git commit -m 'Add amazing feature'
  4. Push to branch: git push origin feature/amazing-feature
  5. Open a Pull Request

πŸ“ Development Setup

# Clone the repo
git clone https://github.com/flaviodelgrosso/fastify-forge.git
cd fastify-forge

# Install dependencies
pnpm install

# Start development
pnpm dev

# Run tests
pnpm test

πŸ“œ License

This project is licensed under the MIT License.


πŸ™ Acknowledgments


Ready to forge your next API? πŸ”₯

npx fastify-forge@latest

Happy coding! πŸš€

About

Fastify armored template to build powerful Node.js web applications πŸ› οΈ

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •