| | |

Netlify 12 ๐ŸŒ Netlify Functions โ€” Building serverless API endpoints with modern Web Request/Response APIs

โฑ๏ธ Estimated read: 8 min | |

Netlify Functions have moved from their legacy, callback-based signatures to a modern, standardized approach using the Web Request and Response APIs. This evolution aligns Netlify Functions with the same standards used in modern browser environments, Node.js, Deno, and Edge runtimes. By using the standard Request and Response objects, developers can write portable, type-safe, and idiomatic code that is easier to test and share across different runtime environments.

This chapter covers the anatomy of the modern Netlify Function handler, how to work with the context object for request metadata, and how to effectively manage payloads using standard body parsing. The sections below will detail the new handler signature, the integration of context for platform capabilities like geo-location, and strategies for handling data streams.

Key point: Modern Netlify Functions use the standard Web Request object for inputs and return a Response object, replacing the legacy (event, context, callback) pattern with a cleaner, asynchronous signature: (request: Request, context: Context) => Promise<Response>.


Why exists

The legacy callback problem.
The original Netlify Functions used a callback patternโ€”(event, context, callback)โ€”which required manually invoking a function to send a response. This made code harder to reason about, prone to errors if callbacks weren’t called, and incompatible with modern async/await patterns that are standard in modern JavaScript.

The standardization problem.
Different platforms historically had proprietary request/response objects. By moving to the Web Standards API (the same objects used in the browser’s fetch API), Netlify enables developers to write code that is portable. You can write your function logic once and run it in a browser, a Node server, or a Netlify Function without changing the interface.

The interoperability problem.
Frameworks like Remix, Next.js, and Astro rely heavily on standard Web APIs. By adopting these standards in Netlify Functions, it becomes trivial to share logic, middleware, and request handlers between your front-end framework and your backend serverless functions.

The context encapsulation problem.
Legacy functions mixed request data, headers, and platform-specific context into one massive event object. The modern approach separates the request (the data coming from the user) from the context (the platform-specific metadata like geolocation, IP, or cookies). This separation makes the handler cleaner and easier to manage.

The runtime portability problem.
Modern runtimes like Deno (used in Edge Functions) and Bun utilize Web Standards natively. By adopting these standards for standard Serverless Functions, Netlify ensures that your code is not tied to a specific runtime implementation, simplifying migration and cross-environment deployment.


a. The Modern Handler Signature

The entry point for a modern Netlify Function is a function that accepts two arguments: the Request object and the Context object. It must return a Promise<Response> or a Response directly. This signature is fundamentally asynchronous, meaning you can use await inside the function body to handle databases, external APIs, or file operations without worrying about callback execution.

import type { Context } from "@netlify/functions";

export default async (request: Request, context: Context) => {
  // Use the standard Response object
  return new Response("Hello from modern Functions!", {
    status: 200,
    headers: { "content-type": "text/plain" },
  });
};

This simple implementation replaces the legacy syntax. The Request object contains everything you need to know about the incoming HTTP requestโ€”the URL, the method, the headers, and the body. The Response object allows you to control the status code, headers, and the body of the response cleanly. This is the idiomatic way to handle HTTP interactions in modern web development.

b. Context and Headers

The Context object is where Netlify injects platform-specific metadata that isn’t part of the standard Request API. This includes information about the user’s location, the server’s region, environment variables, and any cookies that Netlify has intercepted. Because this data is separated from the Request, the request object remains pure and strictly follows the Web standard.

import type { Context } from "@netlify/functions";

export default async (request: Request, context: Context) => {
  // Access location data provided by Netlify's edge layer
  const country = context.geo?.country?.name ?? "Unknown";

  return new Response(`Hello visitor from ${country}!`, {
    headers: { "x-custom-header": "net-val" }
  });
};

Using context is essential when your function logic depends on external factors like user geography. For instance, you can use context.cookies to read session tokens or context.ip to implement rate limiting. Keeping this metadata in the context object keeps your request handler testable, as you can easily mock the context object during unit tests without needing to construct complex, deep-nested event objects.

c. Request Body and Parsing

Working with request bodies follows standard fetch patterns. Since Request.body is a ReadableStream, you can access data using methods like .json(), .text(), or .formData(). This is particularly useful for POST and PUT requests where the client sends serialized data. Since these are asynchronous, you must await them inside your handler.

export default async (request: Request) => {
  if (request.method !== "POST") {
    return new Response("Method not allowed", { status: 405 });
  }

  // Parse JSON body asynchronously
  const data = await request.json();

  return new Response(JSON.stringify({ received: data }), {
    headers: { "content-type": "application/json" }
  });
};

Parsing the body is straightforward but requires care. Always validate the input after parsing, as request.json() will throw an error if the body is not valid JSON. Using standard parsing methods ensures that your function behaves exactly like a modern browser API, making it easy to share validation logic or data-handling utilities between your frontend and your backend.


Complete Example Session

// ============================================
// PART 1: BASIC GET HANDLER
// ============================================
export default async (req: Request) => {
  return new Response("OK", { status: 200 });
};

// ============================================
// PART 2: ACCESSING GEO DATA
// ============================================
import type { Context } from "@netlify/functions";

export default async (req: Request, ctx: Context) => {
  return new Response(`Region: ${ctx.geo?.city}`);
};

// ============================================
// PART 3: JSON POST REQUEST
// ============================================
export default async (req: Request) => {
  const body = await req.json();
  return new Response(JSON.stringify({ ok: true }), {
    headers: { "Content-Type": "application/json" }
  });
};

// ============================================
// PART 4: COOKIE HANDLING
// ============================================
export default async (req: Request, ctx: Context) => {
  const cookie = ctx.cookies.get("session");
  return new Response(`Cookie: ${cookie}`);
};

These parts show the standard flow: setting up a handler, accessing context metadata, parsing JSON payloads, and reading cookies, all using modern Web APIs.


Quick Reference

Handler Signatures

ComponentTypeDescription
RequestWeb StandardIncoming HTTP data
ResponseWeb StandardOutgoing HTTP result
ContextNetlifyGeo, IP, cookies, env

Common Request Operations

ActionMethod
Get JSONawait req.json()
Get Textawait req.text()
Get Headerreq.headers.get('name')
Get URLnew URL(req.url)

Context Capabilities

PropertyReturn TypeUse Case
ctx.geoObjectLocation-based content
ctx.cookiesCookieStoreAuthentication
ctx.ipStringRate limiting

Best Practices

โœ… Do This:

// Always use async/await
export default async (req: Request) => { ... };              // โœ…

// Set explicit headers
return new Response(data, { headers: { "Content-Type": "application/json" } }); // โœ…

// Use URL for parsing params
const url = new URL(req.url);                                 // โœ…

// Validate JSON body
try { const data = await req.json(); } catch(e) { ... }       // โœ…

โŒ Don’t Do This:

// Return non-Response objects
return { message: "Hello" };                                  // โŒ

// Use the legacy callback style
export default (event, ctx, cb) => { cb(null, res); };        // โŒ

// Assume the body is always valid JSON
const data = await req.json(); // No error handling          // โŒ

// Use global variables for state
let count = 0; // State resets between invocations           // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Unhandled JSON errorMalformed request bodyWrap req.json() in try/catch
Missing headerDefault is plain textSet Content-Type explicitly
Callback hellLegacy habitsUse async/await throughout
State leakageGlobal scope relianceUse cookies or DB for persistence

Real-World Examples

1. Basic Response

export default async () => new Response("Hello");

2. JSON Response

return Response.json({ success: true });

3. URL Parameter Extraction

const url = new URL(req.url);
const id = url.searchParams.get("id");

4. Setting Cookies

return new Response("Hi", { headers: { "Set-Cookie": "id=1" } });

5. Handling 404

return new Response("Not Found", { status: 404 });

6. POST with Data

const data = await req.json();

7. Checking Method

if (req.method === "POST") { ... }

8. Using Geo Context

const city = ctx.geo.city;

9. Returning Redirect

return Response.redirect("/new-path");

10. Reading Headers

const auth = req.headers.get("Authorization");

Visual

The Request Lifecycle

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  USER REQUEST                                โ”‚
โ”‚       โ”‚                                      โ”‚
โ”‚       โ–ผ                                      โ”‚
โ”‚  NETLIFY GATEWAY                             โ”‚
โ”‚       โ”‚                                      โ”‚
โ”‚       โ–ผ                                      โ”‚
โ”‚  FUNCTION HANDLER (req, ctx)                 โ”‚
โ”‚       โ”‚                                      โ”‚
โ”‚       โ”‚โ”€โ”€โ–บ Business Logic                    โ”‚
โ”‚       โ”‚                                      โ”‚
โ”‚       โ–ผ                                      โ”‚
โ”‚  RESPONSE OBJECT                             โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Request/Response Mapping

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  INPUT (Request)      OUTPUT (Response)      โ”‚
โ”‚                                              โ”‚
โ”‚  method: "POST"       status: 200            โ”‚
โ”‚  url: "/api/user"     headers: { ... }       โ”‚
โ”‚  body: Stream         body: String/JSON      โ”‚
โ”‚                                              โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Context Object

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  CONTEXT                                     โ”‚
โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”                   โ”‚
โ”‚  โ”‚  Metadata             โ”‚                   โ”‚
โ”‚  โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค                   โ”‚
โ”‚  โ”‚  geo: { city, country}โ”‚                   โ”‚
โ”‚  โ”‚  ip: "123.45.67.89"   โ”‚                   โ”‚
โ”‚  โ”‚  cookies: CookieStore โ”‚                   โ”‚
โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜                   โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Handler Signature

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  (request: Request, context: Context)        โ”‚
โ”‚          โ”‚                 โ”‚                 โ”‚
โ”‚          โ–ผ                 โ–ผ                 โ”‚
โ”‚  Standard HTTP      Platform Data            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Handler patternasync (req, ctx) => Response
InputsRequest, Context
OutputResponse
Body parsingreq.json(), req.text()
Metadatacontext.geo, context.cookies

Key takeaways:

  • Standardization is key. By using Request and Response, your functions are portable and follow the same patterns as modern browser-based fetch logic.
  • Async is required. The modern signature is asynchronous by default, meaning you should always use await when handling bodies or performing I/O.
  • Context separates concerns. Metadata like user geography and authentication cookies live in the context object, keeping the Request object pure and standard.
  • Validation is manual. Parsing methods like req.json() are straightforward but can throw errors; always handle those exceptions gracefully.
  • No global state. Netlify Functions are ephemeral; don’t rely on variables outside the handler to persist across requests.

Remember: Moving to the modern Request/Response signature is about aligning your backend code with the same web standards that power the browser. By separating your platform-specific metadata into the context object and using standard parsing methods, you make your serverless endpoints cleaner, easier to test, and ready for a multi-runtime future.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!