Documentation Sign in to the Console

Writing functions

File names, the request and response, parameters, settings and secrets, logs and packages.

Files and addresses

File Address
api/hello.js /api/hello
api/index.js /api
api/users/[id].js /api/users/42, with context.params.id set to "42"
api/users/me.js /api/users/me (fixed names win over parameters)
api/_shared.js Not an address: files and folders starting with _ are helpers

Files ending in .js, .mjs or .cjs are functions.

The function

Export one default function. It takes a standard Request and returns a standard Response:

js
export default async (request, context) => {
  if (request.method !== "POST") return new Response("Use POST", { status: 405 });
  const body = await request.json();
  return Response.json({ received: body });
};

You can also return:

  • a plain object or array: sent as JSON;
  • a string: sent as text;
  • nothing: an empty 204 response.

The context

Field What
context.params The [name] parts of the file's path
context.ip The visitor's IP address
context.site.host The address the request came to, such as www.example.ca
context.requestId An id for the request, also in the logs

Settings and secrets

Add them on the site's Functions tab (or Settings and secrets when creating the site). They arrive as process.env:

js
export default async () => {
  const res = await fetch("https://api.example.com/v1/rates", {
    headers: { authorization: `Bearer ${process.env.RATES_API_KEY}` },
  });
  return Response.json(await res.json());
};

Secret values are never shown again or returned by the API.

Logs and errors

console.log and console.error go to the logs on the site's Functions tab. If a function throws, the visitor gets a 500 with {"error":"function_error"}, and the stack trace goes to the logs.

Packages

Functions can use Node.js built-ins and fetch. To use packages from npm, bundle them into the file before deploying, for example with esbuild:

bash
npx esbuild src/api/checkout.js --bundle --platform=node --format=esm --outfile=api/checkout.js

Network

Functions can reach the internet. They can't reach Xenkloud's servers, other sites' functions, private addresses or mail ports.