Get started with functions
This page will help you get started with Functions. It describes how to write your functions and route requests to them.
Prepare project
Section titled “Prepare project”Start by adding the @netlify/functions module to your project, which exports all the types you need to create type-safe functions.
npm install @netlify/functionsYou don’t need any additional tooling or configuration to use TypeScript functions, but you can choose to provide your own tsconfig.json file if you want to extend the base configuration in order to rewrite import paths, for example.
Our build system will load any tsconfig.json files from your functions directory, the repository root directory, or the base directory, if set.
Create function file
Section titled “Create function file”To add a serverless function to your project, create a TypeScript file in your functions directory.
You can store your function file directly under the functions directory or in a subdirectory dedicated to the function. If you choose a subdirectory, the function entry file must be named index or have the same name as the subdirectory.
For example, any of the following files would create a function called hello:
netlify/functions/hello.mtsnetlify/functions/hello/hello.mtsnetlify/functions/hello/index.mts
Write a function
Section titled “Write a function”A function file must be written using the JavaScript modules syntax and have a default export with a handler function.
The handler function receives the following arguments:
- A web platform
Requestobject that represents the incoming HTTP request - A Netlify-specific
contextobject with metadata related to the client and the site
For synchronous functions, the return value of the handler function may be used as the HTTP response to be delivered to the client.
Synchronous function
Section titled “Synchronous function”A synchronous function lets you implement a traditional client/server interaction, where the connection is kept open until the function execution is finished, allowing the client to wait for a response before rendering a page or moving on to the next task.
The handler function should return a Response object representing the HTTP response to be delivered to the client, including any caching headers you want to set. If no value is returned, the client will receive an empty response with a 204 status code.
import type { Context } from "@netlify/functions";
export default async (req: Request, context: Context) => { return new Response("Hello, world!")}You can also use context.waitUntil to handle background tasks without delaying the response. This is useful for logging, analytics, or other operations that don’t need to block the client.
import type { Context } from "@netlify/functions";
export default async (req: Request, context: Context) => { context.waitUntil(logRequest(req));
return new Response("Hello, world!");};
async function logRequest(req: Request) { await fetch("https://example.com/log", { method: "POST", body: JSON.stringify({ url: req.url, timestamp: Date.now() }), headers: { "Content-Type": "application/json" }, });}Synchronous functions can stream data to clients as it becomes available, rather than returning a buffered payload at the end of the computation. This lets developers and frameworks create faster experiences by using streaming and partial hydration to get content and interactions in front of people as quickly as possible.
To stream a function’s response, return a ReadableStream as the body property of the Response object.
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);};