Lesson 28 / 30

CORS & Security Headers

Control cross-origin requests and response headers safely.

CORS (Cross-Origin Resource Sharing)

Browsers block cross-origin requests by default. CORS headers tell browsers which origins are allowed to call your API.

Configuring CORS

Use @fastify/cors to control allowed origins, methods, and headers.

import cors from '@fastify/cors';

await fastify.register(cors, {
  origin: ['https://myapp.com', 'http://localhost:3001'],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  credentials: true,
});