Serverless

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.

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.

Note: Using is just one possible way.

app.js

When executed in your lambda function we do not need to listen to a specific port, so we just export the wrapper function in this case. The 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('aws-lambda-fastify')
  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 (make sure you install the dependency npm i --save aws-lambda-fastify) 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 .

Example

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

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. const IS_GOOGLE_CLOUD_RUN = process.env.K_SERVICE !== undefined
  8. // You must listen on the port Cloud Run provides
  9. const port = process.env.PORT || 3000
  10. // You must listen on all IPV4 addresses in Cloud Run
  11. const address = IS_GOOGLE_CLOUD_RUN ? "0.0.0.0" : undefined
  12. try {
  13. const server = build()
  14. const address = await server.listen(port, address)
  15. console.log(`Listening on ${address}`)
  16. } catch (err) {
  17. process.exit(1)
  18. }
  19. }
  20. module.exports = build
  21. if (require.main === module) {
  22. start()
  23. }

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 .

  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 install --only=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:

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

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

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

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

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

provides zero-configuration deployment for Node.js applications. In order 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: