Nandu Singh

Nandu Singh

1628584657

How to enable CORS in a Fastify application

fastify-cors enables the use of CORS in a Fastify application.

Supports Fastify versions 3.x. Please refer to this branch and related versions for Fastify ^2.x compatibility. Please refer to this branch and related versions for Fastify ^1.x compatibility.

Install

npm i fastify-cors

Usage

Require fastify-cors and register it as any other plugin, it will add a preHandler hook and a wildcard options route.

const fastify = require('fastify')()

fastify.register(require('fastify-cors'), { 
  // put your options here
})

fastify.get('/', (req, reply) => {
  reply.send({ hello: 'world' })
})

fastify.listen(3000)

You can use it as is without passing any option or you can configure it as explained below.

Options

  • origin: Configures the Access-Control-Allow-Origin CORS header. The value of origin could be of different types:
    • Boolean - set origin to true to reflect the request origin, or set it to false to disable CORS.
    • String - set origin to a specific origin. For example if you set it to "http://example.com" only requests from "http://example.com" will be allowed. The special * value (default) allows any origin.
    • RegExp - set origin to a regular expression pattern that will be used to test the request origin. If it is a match, the request origin will be reflected. For example, the pattern /example\.com$/ will reflect any request that is coming from an origin ending with "example.com".
    • Array - set origin to an array of valid origins. Each origin can be a String or a RegExp. For example ["http://example1.com", /\.example2\.com$/] will accept any request from "http://example1.com" or from a subdomain of "example2.com".
    • Function - set origin to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback as a second (which expects the signature err [Error | null], origin), where origin is a non-function value of the origin option. Async-await and promises are supported as well. The Fastify instance is bound to function call and you may access via this. For example:
  • methods: Configures the Access-Control-Allow-Methods CORS header. Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: ['GET', 'PUT', 'POST']).
  • allowedHeaders: Configures the Access-Control-Allow-Headers CORS header. Expects a comma-delimited string (ex: 'Content-Type,Authorization') or an array (ex: ['Content-Type', 'Authorization']). If not specified, defaults to reflecting the headers specified in the request's Access-Control-Request-Headers header.
  • exposedHeaders: Configures the Access-Control-Expose-Headers CORS header. Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') or an array (ex: ['Content-Range', 'X-Content-Range']). If not specified, no custom headers are exposed.
  • credentials: Configures the Access-Control-Allow-Credentials CORS header. Set to true to pass the header, otherwise it is omitted.
  • maxAge: Configures the Access-Control-Max-Age CORS header. In seconds. Set to an integer to pass the header, otherwise it is omitted.
  • preflightContinue: Pass the CORS preflight response to the route handler (default: false).
  • optionsSuccessStatus: Provides a status code to use for successful OPTIONS requests, since some legacy browsers (IE11, various SmartTVs) choke on 204.
  • preflight: if needed you can entirely disable preflight by passing false here (default: true).
  • strictPreflight: Enforces strict requirement of the CORS preflight request headers (Access-Control-Request-Method and Origin) as defined by the W3C CORS specification (the current fetch living specification does not define server behavior for missing headers). Preflight requests without the required headers will result in 400 errors when set to true (default: true).
  • hideOptionsRoute: hide options route from the documentation built using fastify-swagger (default: true).

Configuring CORS Asynchronously

const fastify = require('fastify')()

fastify.register(require('fastify-cors'), (instance) => (req, callback) => {
  let corsOptions;
  // do not include CORS headers for requests from localhost
  if (/localhost/.test(origin)) {
    corsOptions = { origin: false }
  } else {
    corsOptions = { origin: true }
  }
  callback(null, corsOptions) // callback expects two parameters: error and options
})

fastify.get('/', (req, reply) => {
  reply.send({ hello: 'world' })
})

fastify.listen(3000)

Acknowledgements

The code is a port for Fastify of expressjs/cors.

License

Licensed under MIT.
expressjs/cors license

origin: (origin, cb) => {
if(/localhost/.test(origin)){
  //  Request from localhost will pass
  cb(null, true)
  return
}
// Generate an error on other origins, disabling access
cb(new Error("Not allowed"))
}

#cors #fastify #node #nodejs 

How to enable CORS in a Fastify application
Nandu Singh

Nandu Singh

1628175900

How to enabled trailing slash in Nest.JS Fastify

Fastify uses find-my-way to handle routing. This option may be set to true to ignore trailing slashes in routes. This option applies to all route registrations for the resulting server instance.

Default: false

const fastify = require('fastify')({
  ignoreTrailingSlash: true
})

// registers both "/foo" and "/foo/"
fastify.get('/foo/', function (req, reply) {
  reply.send('foo')
})

// registers both "/bar" and "/bar/"
fastify.get('/bar', function (req, reply) {
  reply.send('bar')
})

Config in Nest.JS Application 

async function bootstrap() {  
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter({ ignoreTrailingSlash: true })

  );
}

#nestjs #nest #node #nestjs #fastify 

A "fast" Introduction to Fastify

Fastify is a web framework for Node.js that has a great satisfaction across developers with a 89% rating in the last state of javascript. Fastify combines an amazing developer experience with top of the class performance, with minimal reduction on top of Node.js core. In this talk, we will go through the fundamentals of the framework as well as a live coded example.

#fastify #node.js #javascript

A "fast" Introduction to Fastify
Jadyn  Waelchi

Jadyn Waelchi

1626564480

Fastify A Node.js Rest Framework

Fastify a node.js framework, it is a quick look into fastify, what is it how do you use it and some basic validation rules. We will make a mistake and see how the framework response to it. We will dive into some nice features that are different than express.js. It has a lot of plugins, so it is also easy to extend and use the power of the ecosystem.

In my opinion a nice framework that you need to take into account when you are searching for a node.js framework to build big enterprise ready api’s with. The validation hooks are a great and awesome feature of it.

It gets a typewithme approved seal!

https://www.fastify.io/

#fastify #node.js

Fastify A Node.js Rest Framework
Coding  Fan

Coding Fan

1626166378

How To Get Started With Fastify and Next.js using a TypeScript Custom Server

If you’re wanting all the greatness of Next.js without having to deploy on the Vercel platform then look no further, use a custom server with Fastify! 3 main reasons why this is worth it:

  • Use the backend systems you know - ie Fastify - no having to learn how serverless works or how Next.js handles it’s backend API requests in a specific way

  • Keep full access to realtime features - server side events, websockets, socket.io, etc!

  • Don’t get tied to a separate platform when you really want to use Next.js for your next project. Using a Fastify custom server you can containerize your app and be on your way!

Github Repo with working example:

https://github.com/wolfejw86/blog-exa…

Subscribe: https://www.youtube.com/c/JayWolfe/featured

#react #typescript #fastify

How To Get Started With Fastify and Next.js using a TypeScript Custom Server
Landen  Brown

Landen Brown

1626110760

Building a Lightning Fast Serverless API on AWS with Fastify & AWS Amplify

In this video we’ll build and deploy a Fastify web server to AWS, fine tuning the settings to optimize performance and achieve single digit millisecond latency.

Fine tune your Lambda settings with Lambda Power Tuning - https://github.com/alexcasalboni/aws-lambda-power-tuning

Blog post - https://dev.to/aws/deep-dive-finding-the-optimal-resources-allocation-for-your-lambda-functions-35a6

0:00 - Introduction
0:57 - Getting started - creating the project
2:45 - Writing the server
5:45 - Configuring Lambda settings
6:56 - Deploying the backend
7:08 - Testing it out & viewing logs
9:09 - Conclusion

#aws amplify #aws #fastify

Building a Lightning Fast Serverless API on AWS with Fastify & AWS Amplify
Torrey  Kuphal

Torrey Kuphal

1625987731

Fastify vs Express Which is Better? | Fastify TypeScript Tutorial

In this video we take a look at a crash course of Fastify as another web / API framework for NodeJS. We discuss how it is similar or differs from something like ExpressJS. We create a new application from scratch using typescript and the fastify CLI. We also take a look at how JSON Schema factors into the application and how to make that work well with TypeScript.

#fastify #express #typescript #node

Fastify vs Express Which is Better? | Fastify TypeScript Tutorial
Autumn  Blick

Autumn Blick

1625641713

Getting Started with the Notion API

Use Notion to create a database, connect to the Notion API, and create a small Node.js server.

Discover Notion, a project management software similar to Trello and Airtable, and use its API to build the backend of a database.

Notion is a customizable project management software that makes it easy to collaborate on projects and pages, share your work internally or externally, and keep track of teammates.

Notion is easy to use and is a favorite of both tech and non-tech companies. Some popular alternatives to Notion are TrelloJira, and Airtable.

Notion recently released the Notion API, which allows developers to build on top of Notion. While still in public beta, we can use the Notion API to develop and test our own application.

In this tutorial, we’ll use Notion to create a database, connect to the Notion API, and create a small Node.js server that uses Fastify to serve up content from our Notion workspace. Note that this tutorial will only build out the backend of the application.

To follow along with this tutorial, you’ll need to have a basic knowledge of JavaScript and Node.js.

Let’s get started!

#notion #api #node #nodejs #fastify

Getting Started with the Notion API
Coding  Fan

Coding Fan

1625108233

How To Use TDD with Jest and Fastify (Node.js and TypeScript)

Want to see what all the buzz is about with Test Driven Development(TDD)? Look no further! In this video we’ll walk through the TDD thought process using a Fastify healthcheck API along with Jest tests as an example. The process is simple:

1. Think about what your new feature needs to do in the code.

2. Write a test that “expects” your app to do that.

3. Run the test in “watch mode”.

4. Write code until your test passes!

Github Repo with working example:

https://github.com/wolfejw86/blog-exa…

Subscribe: https://www.youtube.com/c/JayWolfe/featured

#jest #fastify

How To Use TDD with Jest and Fastify (Node.js and TypeScript)
Dylan  Iqbal

Dylan Iqbal

1624175083

A Fast Introduction to Fastify (NodeJS Web Framework)

Fastify is a web framework for Node.js that has a great satisfaction across developers with a 89% rating in the last state of javascript. Fastify combines an amazing developer experience with top of the class performance, with minimal reduction on top of Node.js core. In this talk, we will go through the fundamentals of the framework as well as a live coded example.

#fastify #nodejs #node #web-development

A Fast Introduction to Fastify (NodeJS Web Framework)

Fastify Crash Course | Node.js Framework

Fastify is a “fast” Node.js framework. In this video, we will build a REST API with validation schemas and swagger documentation

Code:
https://github.com/bradtraversy/fastify-crash-course

Website & Docs:
https://www.fastify.io/

Timestamps:

  • 0:00 - Intro
  • 2:26 - Install & Setup
  • 3:42 - Basic Server
  • 5:30 - Create a Basic Route
  • 6:33 - VSCode REST Client
  • 7:50 - Data File
  • 11:03 - Separate Routes File
  • 13:30 - Options, Validation Schemas & Handlers
  • 20:25 - Creating a Controller
  • 22:37 - Fastify Swagger API Documentation
  • 24:47 - Add Item POST
  • 30:22 - Body Validation
  • 31:59 - Remove Item DELETE
  • 35:20 - Update Item PUT

#node #fastify #web-development

Fastify Crash Course | Node.js Framework
Alfie Mellor

Alfie Mellor

1620092827

Custom Cache plugin in Fastify using hooks and node-cache

Custom Cache plugin in Fastify using hooks and node-cache.

Timestamps:

  • Intro - 0:00
  • What we’ve done so far - 0:40
  • Setting up the cache plugin and node-cache module - 1:16
  • Setting up the custom cache with hooks (onRequest) - 2:37
  • Setting up the custom cache with hooks (onSend) - 5:12
  • Setting up a TTL for the keys of the cache - 7:05
  • Using Fastify Plugin to enable access from parent context - 7:45
  • Adding function to handle node-cache’s ‘expired’ event - 8:39
  • Adding console logging - 9:33
  • Fixing parameters of ‘expired’ event handler (key, value) - 11:20
  • Testing custom cache - 11:36
  • Outro - 12:43

#fastify

Custom Cache plugin in Fastify using hooks and node-cache

Is Fastify The New Express.js? | Getting Started Tutorial Fastify 2021 Node Framework

In this video I look at Fastify and see why it’s better or not better the Express.js. Then I create a quick CRUD app out of it, and show you how easy it is to work!.

  • 0:00 Introduction
  • 02:15 Installing Fastify And ESM Setup
  • 04:15 Creating Hello World
  • 07:20 Creating Routes
  • 11:05 Setting Up AutoLoad
  • 17:30 Installing and Setting Up Fastify CLI
  • 20:00 Adding A Plugin With Faker
  • 25:04 Adding POST requests
  • 30:52 Setting up validation schema

#express #fastify #node

Is Fastify The New Express.js? | Getting Started Tutorial Fastify 2021 Node Framework

Separation Of Concerns: Example with A Nodejs-Fastify-MongoDB Stack

Building software that works is one thing, building software that last is another, especially when the code size increases rapidly together with the number of people involved in its development.

In this article we will go through some maintainability issues and techniques to avoid them, using a  nodejs web server built with  Fastify (web framework) and  Mongodb (database) as example.

Definition of the web service.

This particular service is a simple  CRUD store for movies, but for many web services, you can scatter in the same way their various components somewhere along a line:

diagram of web service components stack

The bits on the left are very common and have probably little added value for your specific application. The relative value of your service lies in the data you have/collect and what you do with this data (the business logic).

It is important to note that the borders between the layers are not strict and may vary for different projects.

For example, a team with high skills in RDMS can do data aggregation and statistical calculation within a SQL query/function while another team will chose to do the same in the application code, finding it easier to maintain and test.

However, separating the different concerns will ease the maintainability of the codebase anyway, that is what we are going to review here.

#javascript #fastify #clean-code #nodejs

Separation Of Concerns: Example with A Nodejs-Fastify-MongoDB Stack
Alfie Mellor

Alfie Mellor

1619486854

Plugins 101 | Fastify Web Framework for Node.js | REST API Routes, .env, MongoDB

Plugins 101. Fastify web framework for Node.js. REST API Routes, .env, MongoDB.
➥ Repo: https://github.com/pragmatic-reviews/fastify-test/tree/fastify-plugins

Timestamps:

  • Intro - 0:00
  • Refactoring routes as a custom plugin - 0:40
  • Fastify ‘after’ and ‘ready’ methods to handle plugin errors - 3:28
  • Setting up Fastify Env plugin - 4:43
  • Setting up MongoDB plugin and Fastify plugin - 6:48
  • Using MongoDB plugin from routes - 10:33
  • Outro - 12:16

#fastify #node #mongodb

Plugins 101 | Fastify Web Framework for Node.js | REST API Routes,  .env, MongoDB