π What are Netlify Functions?
Netlify Functions allow us to deploy some backend systems. This feature is designed for serverless frameworks, but supports Express.JS as well with some limitations.
ποΈ How to organise your files
To deploy an Express.JS backend to Netlify you need to make sure that your backend meets the following requirements:
β Checklist
Once you have checked your backend meets the requirements, you are ready to add support for Netlify.
βοΈ Define Netlify config
Create or locate a netlify.toml
in your root repository. Append the following code:
[functions]
directory = "server/functions"
external_node_modules = ["express"]
node_bundler = "esbuild"
[[redirects]]
force = true
from = "/api/*"
status = 200
to = "/.netlify/functions/app/:splat"
π§° Add Serverless HTTP
- Create a file called
app.mjs
inside/server/functions
. Make sure it has the following content:
// Netlify wrapper for express.js
import express from "express";
import serverless from "serverless-http";
import apiRouter from "../api";
const app = express();
app.use(express.json());
app.use("/api/", apiRouter);
export const handler = serverless(app);
This will convert your express.JS application into a serverless lambda that is compatible with AWS Lambda and Netlify Functions. Note that this has a large performance impact as your entire express system needs to load up for every single request. Each request runs in isolation so you are unable to share or cache values in your codebase. (For example the database connection will be recreated at every call.)
If you need to use any middleware apart from
express.json()
, include this now.Add
serverless-http
into yourpackage.json
file:
npm i --save serverless-http
πΎ Connect your database
If your backend uses a database, set up a DATABASE_URL
environment variable inside Netlify. This environment variable should point to your database.
π‘ tip
DATABASE_URL
.
π Deploy!
Try deploying your application. Your backend paths should be accessible under https://<name-of-your-app>.netlify.app/api/
If you are stuck, explore FSA Netlify that showcases the above requirements. As an example check this API call