Serverless

Run serverless applications and REST APIs using your existing Fastify application. By default, Fastify will not work on your serverless platform of choice, you will need to make some small changes to fix this. This document contains a small guide for the most popular serverless providers and how to use Fastify with them.

Should you use Fastify in a serverless platform?

That is up to you! Keep in mind that functions as a service should always use small and focused functions, but you can also run an entire web application with them. It is important to remember that the bigger the application the slower the initial boot will be. The best way to run Fastify applications in serverless environments is to use platforms like Google Cloud Run, AWS Fargate, and Azure Container Instances, where the server can handle multiple requests at the same time and make full use of Fastify’s features.

One of the best features of using Fastify in serverless applications is the ease of development. In your local environment, you will always run the Fastify application directly without the need for any additional tools, while the same code will be executed in your serverless platform of choice with an additional snippet of code.

Contents

AWS

To integrate with AWS, you have two choices of library:

  • Using @fastify/aws-lambda which only adds API Gateway support but has heavy optimizations for fastify.
  • Using @h4ad/serverless-adapter which is a little slower as it creates an HTTP request for each AWS event but has support for more AWS services such as: AWS SQS, AWS SNS and others.

So you can decide which option is best for you, but you can test both libraries.

Using @fastify/aws-lambda

The sample provided allows you to easily build serverless web applications/services and RESTful APIs using Fastify on top of AWS Lambda and Amazon API Gateway.

app.js

  1. const fastify = require('fastify');
  2. function init() {
  3. const app = fastify();
  4. app.get('/', (request, reply) => reply.send({ hello: 'world' }));
  5. return app;
  6. }
  7. if (require.main === module) {
  8. // called directly i.e. "node app"
  9. init().listen({ port: 3000 }, (err) => {
  10. if (err) console.error(err);
  11. console.log('server listening on 3000');
  12. });
  13. } else {
  14. // required as a module => executed on aws lambda
  15. module.exports = init;
  16. }

When executed in your lambda function we do not need to listen to a specific port, so we just export the wrapper function init in this case. The lambda.js file will use this export.

When you execute your Fastify application like always, i.e. node app.js (the detection for this could be require.main === module), you can normally listen to your port, so you can still run your Fastify function locally.

lambda.js

  1. const awsLambdaFastify = require('@fastify/aws-lambda')
  2. const init = require('./app');
  3. const proxy = awsLambdaFastify(init())
  4. // or
  5. // const proxy = awsLambdaFastify(init(), { binaryMimeTypes: ['application/octet-stream'] })
  6. exports.handler = proxy;
  7. // or
  8. // exports.handler = (event, context, callback) => proxy(event, context, callback);
  9. // or
  10. // exports.handler = (event, context) => proxy(event, context);
  11. // or
  12. // exports.handler = async (event, context) => proxy(event, context);

We just require @fastify/aws-lambda (make sure you install the dependency npm i @fastify/aws-lambda) and our app.js file and call the exported awsLambdaFastify function with the app as the only parameter. The resulting proxy function has the correct signature to be used as a lambda handler function. This way all the incoming events (API Gateway requests) are passed to the proxy function of @fastify/aws-lambda.

Example

An example deployable with claudia.js can be found here.

Considerations

  • API Gateway does not support streams yet, so you are not able to handle streams.
  • API Gateway has a timeout of 29 seconds, so it is important to provide a reply during this time.

Beyond API Gateway

If you need to integrate with more AWS services, take a look at @h4ad/serverless-adapter on Fastify to find out how to integrate.

Google Cloud Functions

Creation of Fastify instance

  1. const fastify = require("fastify")({
  2. logger: true // you can also define the level passing an object configuration to logger: {level: 'debug'}
  3. });

Add Custom contentTypeParser to Fastify instance

As explained in issue #946, since the Google Cloud Functions platform parses the body of the request before it arrives at the Fastify instance, troubling the body request in case of POST and PATCH methods, you need to add a custom Content-Type Parser to mitigate this behavior.

  1. fastify.addContentTypeParser('application/json', {}, (req, body, done) => {
  2. done(null, body.body);
  3. });

Define your endpoint (examples)

A simple GET endpoint:

  1. fastify.get('/', async (request, reply) => {
  2. reply.send({message: 'Hello World!'})
  3. })

Or a more complete POST endpoint with schema validation:

  1. fastify.route({
  2. method: 'POST',
  3. url: '/hello',
  4. schema: {
  5. body: {
  6. type: 'object',
  7. properties: {
  8. name: { type: 'string'}
  9. },
  10. required: ['name']
  11. },
  12. response: {
  13. 200: {
  14. type: 'object',
  15. properties: {
  16. message: {type: 'string'}
  17. }
  18. }
  19. },
  20. },
  21. handler: async (request, reply) => {
  22. const { name } = request.body;
  23. reply.code(200).send({
  24. message: `Hello ${name}!`
  25. })
  26. }
  27. })

Implement and export the function

Final step, implement the function to handle the request and pass it to Fastify by emitting request event to fastify.server:

  1. const fastifyFunction = async (request, reply) => {
  2. await fastify.ready();
  3. fastify.server.emit('request', request, reply)
  4. }
  5. exports.fastifyFunction = fastifyFunction;

Local test

Install Google Functions Framework for Node.js.

You can install it globally:

  1. npm i -g @google-cloud/functions-framework

Or as a development library:

  1. npm i -D @google-cloud/functions-framework

Then you can run your function locally with Functions Framework:

  1. npx @google-cloud/functions-framework --target=fastifyFunction

Or add this command to your package.json scripts:

  1. "scripts": {
  2. ...
  3. "dev": "npx @google-cloud/functions-framework --target=fastifyFunction"
  4. ...
  5. }

and run it with npm run dev.

Deploy

  1. gcloud functions deploy fastifyFunction \
  2. --runtime nodejs14 --trigger-http --region $GOOGLE_REGION --allow-unauthenticated

Read logs

  1. gcloud functions logs read

Example request to /hello endpoint

  1. curl -X POST https://$GOOGLE_REGION-$GOOGLE_PROJECT.cloudfunctions.net/me \
  2. -H "Content-Type: application/json" \
  3. -d '{ "name": "Fastify" }'
  4. {"message":"Hello Fastify!"}

References

Google Firebase Functions

Follow this guide if you want to use Fastify as the HTTP framework for Firebase Functions instead of the vanilla JavaScript router provided with onRequest(async (req, res) => {}.

The onRequest() handler

We use the onRequest function to wrap our Fastify application instance.

As such, we’ll begin with importing it to the code:

  1. const { onRequest } = require("firebase-functions/v2/https")

Creation of Fastify instance

Create the Fastify instance and encapsulate the returned application instance in a function which will register routes, await the server’s processing of plugins, hooks and other settings. As follows:

  1. const fastify = require("fastify")({
  2. logger: true,
  3. })
  4. const fastifyApp = async (request, reply) => {
  5. await registerRoutes(fastify)
  6. await fastify.ready()
  7. fastify.server.emit("request", request, reply)
  8. }

Add Custom contentTypeParser to Fastify instance and define endpoints

Firebase Function’s HTTP layer already parses the request and makes a JSON payload available. It also provides access to the raw body, unparsed, which is useful in order to calculate request signatures to validate HTTP webhooks.

Add as follows to the registerRoutes() function:

  1. async function registerRoutes (fastify) {
  2. fastify.addContentTypeParser("application/json", {}, (req, payload, done) => {
  3. // useful to include the request's raw body on the `req` object that will
  4. // later be available in your other routes so you can calculate the HMAC
  5. // if needed
  6. req.rawBody = payload.rawBody
  7. // payload.body is already the parsed JSON so we just fire the done callback
  8. // with it
  9. done(null, payload.body)
  10. })
  11. // define your endpoints here...
  12. fastify.post("/some-route-here", async (request, reply) => {}
  13. fastify.get('/', async (request, reply) => {
  14. reply.send({message: 'Hello World!'})
  15. })
  16. }

Export the function using Firebase onRequest

Final step is to export the Fastify app instance to Firebase’s own onRequest() function so it can pass the request and reply objects to it:

  1. exports.app = onRequest(fastifyApp)

Local test

Install the Firebase tools functions so you can use the CLI:

  1. npm i -g firebase-tools

Then you can run your function locally with:

  1. firebase emulators:start --only functions

Deploy

Deploy your Firebase Functions with:

  1. firebase deploy --only functions

Read logs

Use the Firebase tools CLI:

  1. firebase functions:log

References

Google Cloud Run

Unlike AWS Lambda or Google Cloud Functions, Google Cloud Run is a serverless container environment. Its primary purpose is to provide an infrastructure-abstracted environment to run arbitrary containers. As a result, Fastify can be deployed to Google Cloud Run with little-to-no code changes from the way you would write your Fastify app normally.

Follow the steps below to deploy to Google Cloud Run if you are already familiar with gcloud or just follow their quickstart.

Adjust Fastify server

In order for Fastify to properly listen for requests within the container, be sure to set the correct port and address:

  1. function build() {
  2. const fastify = Fastify({ trustProxy: true })
  3. return fastify
  4. }
  5. async function start() {
  6. // Google Cloud Run will set this environment variable for you, so
  7. // you can also use it to detect if you are running in Cloud Run
  8. const IS_GOOGLE_CLOUD_RUN = process.env.K_SERVICE !== undefined
  9. // You must listen on the port Cloud Run provides
  10. const port = process.env.PORT || 3000
  11. // You must listen on all IPV4 addresses in Cloud Run
  12. const host = IS_GOOGLE_CLOUD_RUN ? "0.0.0.0" : undefined
  13. try {
  14. const server = build()
  15. const address = await server.listen({ port, host })
  16. console.log(`Listening on ${address}`)
  17. } catch (err) {
  18. console.error(err)
  19. process.exit(1)
  20. }
  21. }
  22. module.exports = build
  23. if (require.main === module) {
  24. start()
  25. }

Add a Dockerfile

You can add any valid Dockerfile that packages and runs a Node app. A basic Dockerfile can be found in the official gcloud docs.

  1. # Use the official Node.js 10 image.
  2. # https://hub.docker.com/_/node
  3. FROM node:10
  4. # Create and change to the app directory.
  5. WORKDIR /usr/src/app
  6. # Copy application dependency manifests to the container image.
  7. # A wildcard is used to ensure both package.json AND package-lock.json are copied.
  8. # Copying this separately prevents re-running npm install on every code change.
  9. COPY package*.json ./
  10. # Install production dependencies.
  11. RUN npm i --production
  12. # Copy local code to the container image.
  13. COPY . .
  14. # Run the web service on container startup.
  15. CMD [ "npm", "start" ]

Add a .dockerignore

To keep build artifacts out of your container (which keeps it small and improves build times) add a .dockerignore file like the one below:

  1. Dockerfile
  2. README.md
  3. node_modules
  4. npm-debug.log

Submit build

Next, submit your app to be built into a Docker image by running the following command (replacing PROJECT-ID and APP-NAME with your GCP project id and an app name):

  1. gcloud builds submit --tag gcr.io/PROJECT-ID/APP-NAME

Deploy Image

After your image has built, you can deploy it with the following command:

  1. gcloud beta run deploy --image gcr.io/PROJECT-ID/APP-NAME --platform managed

Your app will be accessible from the URL GCP provides.

netlify-lambda

First, please perform all preparation steps related to AWS Lambda.

Create a folder called functions, then create server.js (and your endpoint path will be server.js) inside the functions folder.

functions/server.js

  1. export { handler } from '../lambda.js'; // Change `lambda.js` path to your `lambda.js` path

netlify.toml

  1. [build]
  2. # This will be run the site build
  3. command = "npm run build:functions"
  4. # This is the directory is publishing to netlify's CDN
  5. # and this is directory of your front of your app
  6. # publish = "build"
  7. # functions build directory
  8. functions = "functions-build" # always appends `-build` folder to your `functions` folder for builds

webpack.config.netlify.js

Do not forget to add this Webpack config, or else problems may occur

  1. const nodeExternals = require('webpack-node-externals');
  2. const dotenv = require('dotenv-safe');
  3. const webpack = require('webpack');
  4. const env = process.env.NODE_ENV || 'production';
  5. const dev = env === 'development';
  6. if (dev) {
  7. dotenv.config({ allowEmptyValues: true });
  8. }
  9. module.exports = {
  10. mode: env,
  11. devtool: dev ? 'eval-source-map' : 'none',
  12. externals: [nodeExternals()],
  13. devServer: {
  14. proxy: {
  15. '/.netlify': {
  16. target: 'http://localhost:9000',
  17. pathRewrite: { '^/.netlify/functions': '' }
  18. }
  19. }
  20. },
  21. module: {
  22. rules: []
  23. },
  24. plugins: [
  25. new webpack.DefinePlugin({
  26. 'process.env.APP_ROOT_PATH': JSON.stringify('/'),
  27. 'process.env.NETLIFY_ENV': true,
  28. 'process.env.CONTEXT': env
  29. })
  30. ]
  31. };

Scripts

Add this command to your package.json scripts

  1. "scripts": {
  2. ...
  3. "build:functions": "netlify-lambda build functions --config ./webpack.config.netlify.js"
  4. ...
  5. }

Then it should work fine

Platformatic Cloud

Platformatic provides zero-configuration deployment for Node.js applications. To use it now, you should wrap your existing Fastify application inside a Platformatic Service, by running the following:

  1. npm create platformatic@latest -- service

The wizard would ask you to fill in a few answers:

  1. ? Where would you like to create your project? .
  2. ? Do you want to run npm install? yes
  3. ? Do you want to use TypeScript? no
  4. ? What port do you want to use? 3042
  5. [13:04:14] INFO: Configuration file platformatic.service.json successfully created.
  6. [13:04:14] INFO: Environment file .env successfully created.
  7. [13:04:14] INFO: Plugins folder "plugins" successfully created.
  8. [13:04:14] INFO: Routes folder "routes" successfully created.
  9. ? Do you want to create the github action to deploy this application to Platformatic Cloud dynamic workspace? no
  10. ? Do you want to create the github action to deploy this application to Platformatic Cloud static workspace? no

Then, head to Platformatic Cloud and sign in with your GitHub account. Create your first application and a static workspace: be careful to download the API key as an env file, e.g. yourworkspace.txt.

Then, you can easily deploy your application with the following command:

  1. platformatic deploy --keys `yourworkspace.txt`

Check out the Full Guide on how to wrap Fastify application in Platformatic.

Vercel

Vercel provides zero-configuration deployment for Node.js applications. To use it now, it is as simple as configuring your vercel.json file like the following:

  1. {
  2. "rewrites": [
  3. {
  4. "source": "/(.*)",
  5. "destination": "/api/serverless.js"
  6. }
  7. ]
  8. }

Then, write api/serverless.js like so:

  1. "use strict";
  2. // Read the .env file.
  3. import * as dotenv from "dotenv";
  4. dotenv.config();
  5. // Require the framework
  6. import Fastify from "fastify";
  7. // Instantiate Fastify with some config
  8. const app = Fastify({
  9. logger: true,
  10. });
  11. // Register your application as a normal plugin.
  12. app.register(import("../src/app.js"));
  13. export default async (req, res) => {
  14. await app.ready();
  15. app.server.emit('request', req, res);
  16. }

In src/app.js define the plugin.

  1. async function routes (fastify, options) {
  2. fastify.get('/', async (request, reply) => {
  3. return { hello: 'world' }
  4. })
  5. }
  6. export default routes;