Enhance Your Fastify App with Fastify-CORS A Comprehensive Guide

Introduction to fastify-cors

Fastify-CORS is a Fastify plugin that adds Cross-Origin Resource Sharing (CORS) capabilities to your Fastify applications. CORS is essential for allowing your Fastify server to accept requests from different origins, making it a crucial feature for modern web applications.

Getting Started with fastify-cors

First, you need to install fastify-cors:

  npm install fastify-cors

Once installed, you can register the plugin with your Fastify instance:

  
    const fastify = require('fastify')();
    const fastifyCors = require('fastify-cors');

    fastify.register(fastifyCors, {
      origin: '*'
    });

    fastify.get('/example', (request, reply) => {
      reply.send({ msg: 'CORS is enabled for all origins!' });
    });

    fastify.listen(3000, err => {
      if (err) {
        fastify.log.error(err);
        process.exit(1);
      }
      console.log('Server listening on http://localhost:3000');
    });
  

API Options and Usage

The fastify-cors plugin comes with several options that allow you to customize its behavior:

  • origin: Configures the Access-Control-Allow-Origin header.
  • methods: Configures the Access-Control-Allow-Methods header.
  • allowedHeaders: Configures the Access-Control-Allow-Headers header.
  • exposedHeaders: Configures the Access-Control-Expose-Headers header.
  • credentials: Configures the Access-Control-Allow-Credentials header.
  • maxAge: Configures the Access-Control-Max-Age header.

Examples Using API Options

Here are some examples demonstrating how to use these options:

Specifying Multiple Origins

  
    fastify.register(fastifyCors, {
      origin: ['https://example.com', 'https://another.com']
    });
  

Restricting Methods

  
    fastify.register(fastifyCors, {
      methods: ['GET', 'POST']
    });
  

Allowing Specific Headers

  
    fastify.register(fastifyCors, {
      allowedHeaders: ['Content-Type', 'Authorization']
    });
  

Exposing Headers

  
    fastify.register(fastifyCors, {
      exposedHeaders: ['X-My-Custom-Header', 'X-Another-Custom-Header']
    });
  

Enabling Credentials

  
    fastify.register(fastifyCors, {
      credentials: true
    });
  

Setting Max Age

  
    fastify.register(fastifyCors, {
      maxAge: 86400
    });
  

Complete Example Application

Here’s a complete example of a Fastify app using fastify-cors:

  
    const fastify = require('fastify')();
    const fastifyCors = require('fastify-cors');

    fastify.register(fastifyCors, {
      origin: 'https://example.com',
      methods: ['GET', 'POST'],
      allowedHeaders: ['Content-Type', 'Authorization'],
      exposedHeaders: ['X-My-Custom-Header'],
      credentials: true,
      maxAge: 86400
    });

    fastify.get('/data', (request, reply) => {
      reply.send({ data: 'This route supports CORS!' });
    });

    fastify.listen(3000, err => {
      if (err) {
        fastify.log.error(err);
        process.exit(1);
      }
      console.log('Server listening on http://localhost:3000');
    });
  

Conclusion

Fastify-CORS is a powerful plugin that makes it easy to add CORS support to your Fastify applications. By using the various configuration options, you can fine-tune how your app handles cross-origin requests, ensuring both security and functionality.

Hash: 795f560bdf59c8bac6b7716e4302969cfceeff4386a5a34178dfa21fee234b75

Leave a Reply

Your email address will not be published. Required fields are marked *