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.

Creating a Serverless Function

Every .js (JavaScript) and .ts (TypeScript) 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://[project-subdomain].nhost.run/v1/functions/
functions/users/index.tshttps://[project-subdomain].nhost.run/v1/functions/users
functions/users/active.tshttps://[project-subdomain].nhost.run/v1/functions/users/active
functions/my-company.jshttps://[project-subdomain].nhost.run/v1/functions/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.

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.