Skip to main content

Serverless Functions

With Nhost, you can deploy Serverless Functions to execute custom code. Each serverless function is its HTTP endpoint.

Serverless functions can be used to handle event triggers, form submission, integrations (e.g. Stripe, Slack, etc), and more.


Creating a Serverless Function

Every .js (JavaScript) and .ts (TypeScript) file in the functions/ folder of your Nhost app is its own serverless function.

functions/test.ts
import { Request, Response } from 'express'

export default (req: Request, res: Response) => {
res.status(200).send(`Hello ${req.query.name}!`)
}
info

You MUST install express locally in the base directory of your Nhost app.

npm install -d express @types/express
# or yarn
yarn add -d express @types/express

Deploying Serverless Functions

Serverless functions are automatically deployed using Nhost's GitHub integration.

You can prepend files and folders with an underscore (_) to prevent them from being treated as serverless functions and be turned into HTTP endpoints. This is useful if you have, for example, a utils file (functions/_utils.js) or a utils folder (functions/_utils/[multiple-files].js).

Routing

HTTP endpoints are automatically generated based on the file structure inside functions/.

Here's an example of four serverless functions with their files and their HTTP endpoints:

FileHTTP Endpoint
functions/index.jshttps://[app-subdomain].nhost.run/v1/functions/
functions/users/index.tshttps://[app-subdomain].nhost.run/v1/functions/users
functions/users/active.tshttps://[app-subdomain].nhost.run/v1/functions/users/active
functions/my-company.jshttps://[app-subdomain].nhost.run/v1/functions/my-company

Environment Variables

Environment variables are available inside your serverless functions. Both in production and when running Nhost locally using the Nhost CLI.

Billing

Serverless functions are billed per GB-sec or GB-hour. 1 GB-hour is 3600 GB-seconds.

1 GB-sec is 1 function with 1 GB of RAM running for 1 second. If 1 function with 1 GB of RAM runs for 3600 seconds, that's the equivalent of 1 GB-hour.

All serverless functions in production are running with 128 MB of RAM.

Node Version

All serverless functions in production are running Node.js version 14.x.

Regions

Serverless Functions are always deployed to the same region as your app.