Topics Plugins & Decorators Ecosystem Plugins
intermediate 15 min read

Ecosystem Plugins

Use official Fastify plugins for CORS, rate limiting, compression, and more.

Official Fastify Plugins

// npm install @fastify/cors @fastify/rate-limit @fastify/compress\n// npm install @fastify/multipart @fastify/swagger @fastify/helmet\n\nconst Fastify = require('fastify');\nconst app = Fastify({ logger: true });\n\n// CORS\nawait app.register(require('@fastify/cors'), {\n  origin: ['https://example.com'],\n  methods: ['GET', 'POST', 'PUT', 'DELETE'],\n  credentials: true,\n});\n\n// Rate limiting\nawait app.register(require('@fastify/rate-limit'), {\n  max: 100,\n  timeWindow: '1 minute',\n  keyGenerator: (request) => request.ip,\n});\n\n// Compression\nawait app.register(require('@fastify/compress'), {\n  global: true,\n  brotli: true,\n});\n\n// Swagger documentation\nawait app.register(require('@fastify/swagger'), {\n  openapi: {\n    info: {\n      title: 'My API',\n      version: '1.0.0',\n    },\n  },\n});\n\nawait app.register(require('@fastify/swagger-ui'), {\n  routePrefix: '/docs',\n});\n\n// Health check\nawait app.register(require('@fastify/under-pressure'), {\n  maxEventLoopDelay: 1000,\n  maxHeapUsedBytes: 100000000,\n});

Examples

const Fastify = require('fastify');

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

// Register common plugins
async function buildApp() {
  // CORS
  await app.register(require('@fastify/cors'), {
    origin: true,
    credentials: true,
  });

  // Rate limit
  await app.register(require('@fastify/rate-limit'), {
    max: 100,
    timeWindow: '1 minute',
  });

  // Request body size limit
  await app.register(require('@fastify/multipart'), {
    limits: {
      fileSize: 5 * 1024 * 1024, // 5MB
    },
  });

  // Health check endpoint
  app.get('/health', async () => ({
    status: 'healthy',
    uptime: process.uptime(),
    timestamp: new Date().toISOString(),
  }));

  // A simple API
  app.get('/api/items', async () => ({
    data: [{ id: 1, name: 'Item 1' }],
    timestamp: new Date().toISOString(),
  }));

  return app;
}

buildApp()
  .then(app => app.listen({ port: 3000 }))
  .catch(err => {
    console.error(err);
    process.exit(1);
  });

Your Notes

Sign in to take notes for this lesson.

Quiz

Plugins & Decorators Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.