Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Serverless and Edge Functions

Netlify Functions

Write Netlify Functions with the modern Request and Response signature: file layout, custom paths, the context object, environment variables, local testing with netlify dev and error handling.

Netlify Functions let you add backend endpoints to a Netlify site. You place a file in a folder, deploy, and it becomes an HTTP endpoint. Under the hood they run on a cloud function service, but you never configure that yourself.

This lesson uses the modern function format (a default export that receives a Request and a context and returns a Response). Older code you may find online uses an exports.handler = async (event) => ... style; it still works but the modern one is simpler and matches web standards.

Where functions live

By default, Netlify looks in netlify/functions at the root of your project. You can change the folder in netlify.toml:

TOML
[build]
  functions = "netlify/functions"
TEXT
my-site/
  netlify/
    functions/
      hello.js
      subscribe.js
      users/
        index.js        # becomes the function named "users"
  netlify.toml

A file hello.js becomes reachable at /.netlify/functions/hello. A folder with an index.js also works. Files can be .js, .mjs, .ts and more; Netlify bundles them (including npm dependencies) when you deploy.

Your first function

JavaScript
// netlify/functions/hello.js
export default async (request, context) => {
  const url = new URL(request.url);
  const name = url.searchParams.get("name") ?? "world";

  return new Response(JSON.stringify({ message: `Hello, ${name}!` }), {
    status: 200,
    headers: { "Content-Type": "application/json" },
  });
};

Call it from your site's JavaScript:

JavaScript
const res = await fetch("/.netlify/functions/hello?name=Ada");
const data = await res.json();

A nicer URL with config.path

Export a config object to give the function a clean route, including dynamic segments:

JavaScript
// netlify/functions/post.js
export default async (request, context) => {
  return Response.json({ id: context.params.id });
};

export const config = {
  path: "/api/posts/:id",
};

Now /api/posts/42 calls the function with context.params.id === "42". You can also limit methods inside your code by checking request.method.

The context object

The second argument carries information about the request and the Netlify environment. Commonly used fields (check the current documentation for the full list):

  • context.params: values from the path pattern.
  • context.geo: approximate location of the visitor (country, city, and so on).
  • context.ip: the client IP address.
  • context.cookies: helpers to read and set cookies.
  • context.site: information about the site.
  • context.deploy: details such as the deploy ID and context.

Read environment variables with Netlify.env.get("NAME") (or process.env.NAME in Node-based functions).

A router you can run

Dynamic path patterns are the part people get wrong. This stand-in implements the matching logic so you can see how :id segments become params. It is a teaching model, not Netlify's router.

Node.js Path pattern matching (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A full example: a subscribe endpoint

JavaScript
// netlify/functions/subscribe.js
export default async (request) => {
  if (request.method !== "POST") {
    return new Response("Method Not Allowed", { status: 405, headers: { Allow: "POST" } });
  }
  const { email } = await request.json().catch(() => ({}));
  if (!email || !email.includes("@")) {
    return Response.json({ error: "A valid email is required" }, { status: 422 });
  }

  // Replace with a real call to your email service, using a secret
  // stored as an environment variable:
  // await fetch("https://mail.example.test/subscribe", {
  //   method: "POST",
  //   headers: { Authorization: `Bearer ${Netlify.env.get("MAIL_API_KEY")}` },
  //   body: JSON.stringify({ email }),
  // });

  return Response.json({ ok: true }, { status: 201 });
};

export const config = { path: "/api/subscribe" };

Here is the same logic as a local test. It imitates how the platform calls the default export with a Request, so you can check status codes before deploying.

Node.js Testing the subscribe handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Testing locally

Run netlify dev in your project. It serves your site, runs functions at /.netlify/functions/NAME and at any config.path routes, injects the site's environment variables, and reloads on changes. You can also invoke a function from the terminal with netlify functions:invoke hello --querystring "name=Ada". After deploying, find logs in the dashboard under Logs > Functions or with netlify logs:function.

Common mistakes

  • Wrong folder name. The folder must match the functions setting; otherwise the function is silently not deployed.
  • Forgetting to await a promise, so the function returns before work finishes.
  • Returning a plain object instead of a Response in the modern format.
  • Hard-coding secrets. Use environment variables scoped to the Functions scope.
  • CORS. Calls from your own site on the same domain do not need it; calls from other origins do, and you must send the right headers yourself.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does Netlify look for functions by default?

    The default functions directory is netlify/functions, configurable in netlify.toml.
  2. 2. What does the modern handler return?

    Modern functions return a Web-standard Response.
  3. 3. How do you give a function the route /api/posts/:id?

    export const config = { path: ... } maps routes, and context.params holds the values.
  4. 4. Which command runs functions locally with site variables?

    netlify dev emulates the platform locally, including functions.

Summary

  • Netlify Functions live in netlify/functions and are exposed at /.netlify/functions/NAME or a custom config.path.
  • The modern signature is export default async (request, context) => Response.
  • context.params, context.geo and cookies give request details; read secrets with Netlify.env.get.
  • Test with netlify dev and inspect logs in the dashboard or CLI.
  • Validate input, use correct status codes and never hard-code secrets.

Next: Vercel Functions