Skip to content
For the complete Netlify documentation index, see llms.txt. Markdown versions of this page are available by appending .md to the URL.

Unlimited seats on Netlify Pro for $20/month → Learn more 👥

Functions API reference

For the complete documentation index, see llms.txt

This page provides a full reference of the Netlify Serverless Functions API.

A function file exports a default handler that runs in response to an event. The signature depends on the type of event the function responds to.

A function that responds to web requests receives a Request representing the incoming request and a Context object with Netlify-specific metadata. The handler returns a Response.

Two equivalent forms are supported:

import type { Context } from "@netlify/functions"
export default async (req: Request, context: Context) => {
return new Response("Hello, world!")
}

The second form is a Fetchable module, a common shape for fetch-style handlers across JavaScript frameworks and runtimes.

When config.background is set to true, the platform sends a 202 response to the client immediately and the function continues running in the background, up to the background execution limit. The handler’s return value is discarded.

For more details, see Background Functions.

A function can stream data to clients as it becomes available, instead of returning a buffered payload after the function finishes. To stream a response, return a ReadableStream as the body of the Response.

Streaming functions have a 10-second execution limit and a 20 MB response size limit.

Emit a list of timestamped items over the course of several seconds:

export default async () => {
const encoder = new TextEncoder()
const formatter = new Intl.DateTimeFormat("en", { timeStyle: "medium" })
const body = new ReadableStream({
start(controller) {
controller.enqueue(encoder.encode("<html><body><ol>"))
let i = 0
const timer = setInterval(() => {
controller.enqueue(encoder.encode(`<li>Hello at ${formatter.format(new Date())}</li>\n\n`))
if (i++ >= 5) {
controller.enqueue(encoder.encode("</ol></body></html>"))
controller.close()
clearInterval(timer)
}
}, 1000)
},
})
return new Response(body)
}

A function can subscribe to events that occur in your Netlify project, such as a deploy completing or a user signing up. To subscribe, export an object whose properties are named after the events you want to handle.

import type { DeploySucceededEvent } from "@netlify/functions"
export default {
deploySucceeded(event: DeploySucceededEvent) {
console.log(`Deploy ${event.deploy.id} shipped`)
},
}

Platform event handlers always run in the background; no response is delivered to a client. You can combine them with a fetch handler to serve web requests from the same function.

For the full list of supported events and their payloads, see Trigger functions on events.

The Context object exposes the following properties:

An object containing Netlify team account information. The id property in the object holds the unique ID of the team that the site and function belong to.

A simplified interface for reading and storing cookies:

  • cookies.get(name): reads a cookie with a given name from the incoming request.

  • cookies.set(options): sets a cookie on the outgoing response, using the same format as the options value in the CookieStore.set web standard.

  • cookies.delete(name) or cookies.delete(options): adds an instruction to the outgoing response for the client to delete a cookie. Following the CookieStore.delete web standard, accepts a string representing the name of the cookie, or an options object.

An object containing Netlify deploy information with the following property:

  • context: the context of the deploy that the function belongs to.
  • id: unique ID of the deploy that the function belongs to.
  • published: a boolean that indicates whether or not the function belongs to the current published deploy.
  • skewProtectionToken: a token that can be used to uniquely identify the deploy in HTTP calls when skew protection is enabled.

An object containing geolocation data for the client with the following properties:

  • city: name of the city.
  • country:
    • code: ISO 3166 code for the country.
    • name: name of the country.
  • latitude: latitude of the location.
  • longitude: longitude of the location.
  • subdivision:
    • code: ISO 3166 code for the country subdivision.
    • name: name of the country subdivision.
  • timezone: timezone of the location.
  • postalCode: postal (zip) code of the location. We support all regional formats, so the format will vary.

A string containing the client IP address.

An object containing the parameters set for the function’s path in the configuration object and the values they receive from the incoming request URL.

For example, for a function configured to run at /pets/:name, the params value for a request to /pets/boo will be {"name":"boo"}.

To access the query string, use request.url instead.

A string containing the Netlify request ID.

For example, 01FDWR77JMF2DA1CHF5YA6H07C.

An object containing server metadata with the following property:

  • region: the region code where the deployment is running; for example, us-east-1.

An object containing Netlify site metadata with the following properties:

  • id: unique ID for the site; for example, 1d01c0c0-4554-4747-93b8-34ce3448ab95.
  • name: name of the site, its Netlify subdomain; for example, petsof.
  • url: URL representing the main address to your site. It can be either a Netlify subdomain or your own custom domain if you set one; for example, https://petsof.netlify.app or https://www.petsofnetlify.com.

context.waitUntil() is a function that implements the ExtendableEvent.waitUntil standard. It allows you to extend the function’s execution until the given Promise it completed, without blocking the response to the client from being sent.

You can use it to perform any tasks after the response is sent, such as emitting analytics events or dispatching logs.

Usage notes:

  • This method is available for functions deployed on or after March 20, 2025. To test locally, use the latest version of the Netlify CLI.
  • The duration which is reported in logs, reported in metrics, exported via log drains and used for billing includes the full duration of the function until it completes, including any asynchronous operations. Typically, the end-user is receiving the response before the function completes all async work.
  • The Netlify function can run until its execution time limit. That includes all async work.

The Config object configures how a function is deployed and invoked. Export it from your function file as a config constant, or place it inside the config property of a Fetchable module default export.

For task-oriented descriptions of each setting with full examples, see Configuration for functions.

Type: boolean

When true, the function runs in background mode.

Type: string | string[]

One or more URL paths for which the function will not run, even if they also match path. Paths must begin with a forward slash. See Routing.

Type: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS', or an array of those values

Limits the HTTP methods that invoke the function. If not set, the function runs for all supported methods.

Type: number | string

The maximum amount of memory (in MB) the function can use. Accepts either a number (2048) or a human-friendly string ("2gb", "1024mb"). Mutually exclusive with vcpu. See Memory or vCPU.

Type: string | string[]

One or more URL paths for which the function will run. Paths must begin with a forward slash. Mutually exclusive with schedule. See Routing.

Type: boolean

When true, the function only runs when no matching static file exists at the request URL.

Type: object

Sets rate-limiting rules for the function. See Rate limiting.

Properties:

  • action: 'rate_limit' or 'rewrite'. The behavior to apply when the limit is exceeded.
  • aggregateBy: 'domain' or 'ip', or an array of both. Determines how requests are grouped.
  • to: a string. When action is 'rewrite', the path to rewrite to.
  • windowSize: a number. The time window in seconds.
  • windowLimit: a number. The maximum number of requests permitted in the window.

Type: airport code (for example, 'iad')

The region where the function should be deployed. See Region for the list of supported values.

Type: cron expression

A cron expression that schedules the function. When set, the function runs on the schedule and does not accept incoming web requests. Mutually exclusive with path and excludedPath. See Scheduled Functions.

Type: number

The number of vCPUs to allocate. Allowed range is 0.5 to 2. Mutually exclusive with memory. See Memory or vCPU.

@netlify/functions is a small package that provides types and helpers for writing Netlify Functions.

Terminal window
npm install @netlify/functions

Returns the Context object for the current request. Useful in scopes where you can’t directly access the handler arguments — for example, inside a web framework or another abstraction layer that wraps the underlying function handler.

Throws when called outside an active request. If you have legitimate call sites that may or may not run inside a request, wrap the call in try/catch.

import { getContext, type Config, type Context } from "@netlify/functions"
const getResponseFromDifferentScope = () => {
const city = getContext().geo?.city ?? "somewhere"
return new Response(`Hello from ${city}`)
}
export default async (req: Request, context: Context) => {
return getResponseFromDifferentScope()
}
export const config: Config = {
path: "/hello",
}

Invalidates content cached on Netlify’s edge cache (function responses, static assets, edge function responses, and any other cacheable content) directly from inside a function. The site ID and authentication are inferred from the function’s runtime environment.

import { purgeCache } from "@netlify/functions"
export default async () => {
await purgeCache()
return new Response("Purged!", { status: 202 })
}

Accepts an optional options object:

  • tags: an array of cache tag strings to invalidate. Omit to purge everything for the site.
  • deployAlias: limits the purge to a specific deploy alias (for example, 'deploy-preview-11').
  • token: a purge API token. Defaults to the NETLIFY_PURGE_API_TOKEN environment variable.
  • userAgent: a custom user-agent string for the API call.
  • siteID, siteSlug, or domain (mutually exclusive): identifies the target site. Defaults to the site ID provided by the runtime.

For usage patterns, see On-demand cache invalidation.

The package exports the following TypeScript types:

  • Context, Config, NetlifyFunction: handler argument shapes, configuration object, and the full function shape for Fetchable module functions.
  • Event types for platform events: DeployBuildingEvent, DeploySucceededEvent, DeployFailedEvent, DeployDeletedEvent, DeployLockedEvent, DeployUnlockedEvent, UserLoginEvent, UserSignupEvent, UserValidateEvent, UserModifiedEvent, UserDeletedEvent, FormSubmittedEvent.
  • Handler types for platform events: DeploySucceededHandler, UserLoginHandler, and so on — one per event type.

For details on each event’s payload, see Trigger functions on events.

The @netlify/aws-lambda-compat package lets you author Netlify Functions using the AWS Lambda handler signature, while running on the modern Netlify Functions runtime with full access to platform primitives and zero-config features.

Terminal window
npm install @netlify/aws-lambda-compat

Wraps a Lambda-style handler and returns a modern Netlify function. Use the result as your function’s default export:

import { withLambda } from "@netlify/aws-lambda-compat"
import type { HandlerContext, HandlerEvent, HandlerResponse } from "@netlify/aws-lambda-compat"
export default withLambda(async (event: HandlerEvent, context: HandlerContext): Promise<HandlerResponse> => {
const name = event.queryStringParameters?.name ?? "World"
return {
statusCode: 200,
headers: { "content-type": "application/json" },
body: JSON.stringify({ message: `Hello, ${name}!` }),
}
})

The wrapper:

  • Builds a HandlerEvent from the incoming web Request (URL, headers, query string, and body — with automatic base64 encoding for binary payloads).
  • Maps the Netlify Context onto a HandlerContext, populating AWS-specific fields with sensible defaults.
  • Converts the HandlerResponse returned by your handler back into a web-standard Response.

The package exports the following TypeScript types:

  • LambdaHandler: the handler signature accepted by withLambda.
  • Handler, HandlerCallback: the AWS Lambda handler shapes, for compatibility with code that imports them from aws-lambda or legacy @netlify/functions typings.
  • HandlerEvent, HandlerContext, HandlerResponse: the event, context, and response shapes used by Lambda-style handlers.