typescriptbeginner

Fastify Server Setup

Create a high-performance Fastify server with schema validation, plugins, and typed routes.

typescript
import Fastify from 'fastify';

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

// JSON Schema for validation
const getUserSchema = {
  params: {
    type: 'object' as const,
    properties: { id: { type: 'string' } },
    required: ['id'],
  },
  response: {
    200: {
      type: 'object' as const,
      properties: {
        id: { type: 'string' },
        name: { type: 'string' },
        email: { type: 'string' },
      },
    },
  },
};

// Routes
app.get('/health', async () => ({ status: 'ok', uptime: process.uptime() }));

app.get<{ Params: { id: string } }>(
  '/users/:id',
  { schema: getUserSchema },
  async (request, reply) => {
    const { id } = request.params;
    return { id, name: 'Alice', email: 'alice@example.com' };
  },
);

app.post<{ Body: { name: string; email: string } }>(
  '/users',
  {
    schema: {
      body: {
        type: 'object' as const,
        properties: {
          name: { type: 'string', minLength: 1 },
          email: { type: 'string', format: 'email' },
        },
        required: ['name', 'email'],
      },
    },
  },
  async (request, reply) => {
    reply.code(201);
    return { id: crypto.randomUUID(), ...request.body };
  },
);

app.listen({ port: 3000 }, (err) => {
  if (err) { app.log.error(err); process.exit(1); }
});

Sponsored

Railway

Use Cases

  • High-performance REST APIs
  • Type-safe API routes
  • Schema-validated endpoints

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.