Login
A chronicle of the thoughts, learning experiences, ideas and actions of a tech junkie, .NET, JS and Mobile dev, aspiring entrepreneur, devout Christian and travel enthusiast.
[HOW TO] Add CORS Support to your Fastify app
I have been developing web APIs with ExpressJS running on Node for a few years and while I had heard about Fastify, I hadn't ever felt the need to use it until I decided to create a mini language and framework benchmark and decided to take a look and its performance blew me away.
Since then, I decided to develop a new project using the Fastify framework and one of the first things that need to be added to a new API is support for Cross-Origin Resource Sharing (CORS). For those who may not know what CORS is, Mozilla defines CORS as " an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources". Which, when simplified is a system that allows your API to handle requests from any source based on the CORS policy you create.
For this guide, the assumption is made that you already have your Fastify project set with at least basic API initialization logic set.
To start, you would need the fastify-cors
package from NPM. Depending on your package manager, you can run any of the following commands:
npm i fastify-cors
or
yarn add fastify-cors
In the file that holds your API initialization logic, some may name theirs main.js
, server.js
or index.js
, import the cors package you just installed:
const fastify = require('fastify');
...
const cors = require('fastify-cors');
With that done, we register it with Fastify as middleware as follows:
fastify.register(cors, { });
If you want to customize the functions of the middleware, you can change those parameters by adding the updated fields to the second parameter passed to the fastify.register()
call.
fastify.register(cors, {
// make customizations here
});
Some of the properties that can be seen on the official documentation page
I generally feel excited to share the things I learn with anyone who'll listen and if this has been helpful, feel free to let me know!
Cheers!
Comments