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 submissions, integrations (e.g. Stripe, Slack, etc), and more.

Create a Serverless Function

Every .ts (TypeScript) and .js (JavaScript) file in the functions/ folder of your Nhost project 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

To get the Request, and Response types you can install the @types/express package.

npm install -D @types/express
# or yarn
yarn add -D @types/express
# or pnpm
pnpm add -D @types/express

Deploying Serverless Functions

Serverless Functions are automatically deployed using Nhost's Git integration.

All Serverless Functions are deployed with the following options:

  • Node v16
  • 1024 MB memory (can be upgraded)
  • 10 seconds timeout (can be upgraded)
  • 6 MB request and response payload size limit

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://[subdomain].functions.[region].nhost.run/v1/
functions/users/index.tshttps://[subdomain].functions.[region].nhost.run/v1/users
functions/users/active.tshttps://[subdomain].functions.[region].nhost.run/v1/users/active
functions/my-company.jshttps://[subdomain].functions.[region].nhost.run/v1/my-company

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-f older (functions/_utils/<utils-files>.js).

Environment Variables

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

The same environment variables that are used to configure event triggers can be used to authenticate regular serverless functions.

Examples

We have multiple examples of Serverless Functions in our Nhost repository.

Billing

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

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

Regions

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

Local Debugging

Use nhost logs functions -f to see the logs of your Serverless Functions when develop locally with the Nhost CLI.