For the complete Netlify documentation index, see llms.txt. Markdown versions of this page are available by appending .md to the URL. This page provides a full reference of the Netlify Serverless Functions API.
Function signature
Section titled “Function signature”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.
Web requests
Section titled “Web requests”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!")}import type { NetlifyFunction } from "@netlify/functions"
export default { fetch: (req, context) => { return new Response("Hello, world!") },} satisfies NetlifyFunctionThe second form is a Fetchable module, a common shape for fetch-style handlers across JavaScript frameworks and runtimes.
Background mode
Section titled “Background mode”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.
Streaming responses
Section titled “Streaming responses”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)}Streaming services like OpenAI’s Chat Completions API return a Response whose body is already a ReadableStream. If you don’t need to transform the bytes, you can pass res.body directly into your own Response and the tokens stream straight through to the client:
export default async (req: Request) => { const pie = new URL(req.url).searchParams.get("pie") ?? "a springtime garden"
const res = await fetch("https://api.openai.com/v1/chat/completions", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, }, body: JSON.stringify({ model: "gpt-4o-mini", messages: [ { role: "system", content: "You are a baker. The user will ask you for a pie recipe. Respond in markdown.", }, { role: "user", content: pie.slice(0, 500) }, ], stream: true, }), })
return new Response(res.body, { headers: { "content-type": "text/event-stream" }, })}Wrap the Groq SDK’s streaming completion in a ReadableStream:
import Groq from "groq-sdk"
const client = new Groq({ apiKey: process.env.GROQ_API_KEY })
export default async (req: Request) => { const pie = new URL(req.url).searchParams.get("pie") ?? "a springtime garden"
const stream = await client.chat.completions.create({ model: "llama3-8b-8192", messages: [ { role: "system", content: "You are a baker. The user will ask you for a pie recipe. Respond in markdown.", }, { role: "user", content: pie.slice(0, 500) }, ], temperature: 0.5, max_tokens: 1024, stream: true, })
const readableStream = new ReadableStream({ async start(controller) { for await (const chunk of stream) { controller.enqueue(new TextEncoder().encode(chunk.choices[0]?.delta?.content || "")) } controller.close() }, })
return new Response(readableStream, { headers: { "content-type": "text/event-stream" }, })}Platform events
Section titled “Platform events”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.
Context object
Section titled “Context object”The Context object exposes the following properties:
account
Section titled “account”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.
cookies
Section titled “cookies”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 theoptionsvalue in theCookieStore.setweb standard. -
cookies.delete(name)orcookies.delete(options): adds an instruction to the outgoing response for the client to delete a cookie. Following theCookieStore.deleteweb standard, accepts a string representing the name of the cookie, or an options object.
deploy
Section titled “deploy”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.
params
Section titled “params”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.
requestId
Section titled “requestId”A string containing the Netlify request ID.
For example, 01FDWR77JMF2DA1CHF5YA6H07C.
server
Section titled “server”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.apporhttps://www.petsofnetlify.com.
waitUntil
Section titled “waitUntil”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.
Config object
Section titled “Config object”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.
background
Section titled “background”Type: boolean
When true, the function runs in background mode.
excludedPath
Section titled “excludedPath”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.
method
Section titled “method”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.
memory
Section titled “memory”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.
preferStatic
Section titled “preferStatic”Type: boolean
When true, the function only runs when no matching static file exists at the request URL.
rateLimit
Section titled “rateLimit”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. Whenactionis'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.
region
Section titled “region”Type: airport code (for example, 'iad')
The region where the function should be deployed. See Region for the list of supported values.
schedule
Section titled “schedule”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
Section titled “@netlify/functions”@netlify/functions is a small package that provides types and helpers for writing Netlify Functions.
npm install @netlify/functionsgetContext()
Section titled “getContext()”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",}purgeCache()
Section titled “purgeCache()”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 theNETLIFY_PURGE_API_TOKENenvironment variable.userAgent: a custom user-agent string for the API call.siteID,siteSlug, ordomain(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.
@netlify/aws-lambda-compat
Section titled “@netlify/aws-lambda-compat”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.
npm install @netlify/aws-lambda-compatwithLambda()
Section titled “withLambda()”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
HandlerEventfrom the incoming webRequest(URL, headers, query string, and body — with automatic base64 encoding for binary payloads). - Maps the Netlify
Contextonto aHandlerContext, populating AWS-specific fields with sensible defaults. - Converts the
HandlerResponsereturned by your handler back into a web-standardResponse.
The package exports the following TypeScript types:
LambdaHandler: the handler signature accepted bywithLambda.Handler,HandlerCallback: the AWS Lambda handler shapes, for compatibility with code that imports them fromaws-lambdaor legacy@netlify/functionstypings.HandlerEvent,HandlerContext,HandlerResponse: the event, context, and response shapes used by Lambda-style handlers.
Did you find this doc useful?
Your feedback helps us improve our docs.