Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท Serverless and Edge Functions

Vercel Functions

Write Vercel Functions in the api folder or as framework route handlers: method exports, dynamic routes, configuration for duration and region, streaming and testing with vercel dev.

On Vercel, backend code is a Vercel Function. You can write one in two ways: as a plain file in an api/ folder, which works in any project, or as a route in a framework that has its own server routes (Next.js route handlers, SvelteKit endpoints, Nuxt server routes and others). Both are deployed as functions automatically.

This lesson covers the standalone api/ style and the web-standard handler shape, which is also what Next.js route handlers use.

The api/ folder

Any file under api/ in your project root becomes an endpoint. The file path is the URL path.

TEXT
my-project/
  api/
    hello.js            -> /api/hello
    users/
      index.js          -> /api/users
      [id].js           -> /api/users/42   (dynamic segment)
  public/
  package.json

Square brackets mark a dynamic segment. A file [id].js matches any single segment. [...slug].js is a catch-all.

Method handlers with web standards

Export a function named after the HTTP method. Each receives a Request and returns a Response:

JavaScript
// api/hello.js
export function GET(request) {
  const name = new URL(request.url).searchParams.get("name") ?? "world";
  return Response.json({ message: `Hello, ${name}!` });
}

export async function POST(request) {
  const body = await request.json();
  return Response.json({ received: body }, { status: 201 });
}

If a method is not exported, requests with that method receive a "405 Method Not Allowed" response. You can also use a single fetch export that handles every method:

JavaScript
export default {
  async fetch(request) {
    return new Response("Hello from fetch");
  },
};

Vercel's documentation also describes an older Node.js style that receives (req, res) objects (similar to Express). It remains supported, but the web-standard style is portable and easy to test.

Dynamic segments

In the web-standard style, read the dynamic part from the URL. In framework route files (for example Next.js app/api/users/[id]/route.js) the framework passes it as params.

JavaScript
// api/users/[id].js
export function GET(request) {
  const id = new URL(request.url).pathname.split("/").pop();
  return Response.json({ id });
}

Routing stand-in

This stand-in maps file paths to URLs and extracts dynamic values, mimicking file-based routing. It is a teaching model and not the platform's routing engine.

Node.js File-based routing (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.

Testing a handler locally

Because the handlers are plain functions of Request to Response, you can test them without any platform.

Node.js Testing GET and POST handlers

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.

For a live check, run vercel dev in your project: it serves your framework plus the api/ routes locally with your Development environment variables.

Configuring a function

Settings such as the maximum duration, memory and region can be set per function in vercel.json:

JSON
{
  "functions": {
    "api/report.js": { "maxDuration": 30 },
    "api/**/*.js": { "memory": 512 }
  }
}

Frameworks like Next.js also let you export route segment options from the file itself (for example export const maxDuration = 30;). The allowed ranges depend on your plan and on the platform's current compute model, so check the current limits before depending on a number. You can also pick the region where functions run; place them near your database to avoid slow cross-continent queries.

Streaming responses

A handler may return a Response whose body is a stream, which lets the browser start rendering before the function finishes. This is how AI chat output and large server-rendered pages feel fast.

Node.js Streaming a response

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.

Environment and logging

Read secrets with process.env.NAME. console.log output appears in the deployment's runtime logs (dashboard Logs tab or vercel logs). Log identifiers and results, not secrets or personal data.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A file at api/users/[id].js is reachable at which URL?

    Brackets mark a dynamic segment, so any value in that position matches.
  2. 2. What happens if a file exports only GET and receives a POST?

    Unexported methods are not allowed.
  3. 3. Where do you raise a function's maximum duration for a standalone api file?

    The functions object maps file patterns to settings such as maxDuration and memory.
  4. 4. Why place functions in a region near your database?

    Shorter network distance makes database calls faster.

Summary

  • Files under api/ become endpoints; brackets in file names define dynamic segments.
  • Export GET, POST and other method functions that take a Request and return a Response.
  • Test handlers locally as plain functions and with vercel dev.
  • Configure duration, memory and region in vercel.json or framework options; check current plan limits.
  • Streaming responses let clients start receiving data early.

Next: Edge Functions and Middleware