Skip to content

Basic examples

HTTP triggers expose a public endpoint.

The simplest endpoint returns a simple JSON message:

View and run this example on Val Town

export const jsonOkExample = () => Response.json({ ok: true });

Or you could return HTML with the corresponding Content-Type header:

View and run this example on Val Town

export const htmlExample = () =>
new Response("<h1>Hello, world</h1>", {
headers: {
"Content-Type": "text/html",
},
});

This echoes request headers back in the response:

View and run this example on Val Town

export const headersExample = (request: Request) => {
return Response.json(Object.fromEntries(request.headers.entries()));
};

We can get and return the request URL’s query parameters:

View and run this example on Val Town

export const queryParams = (req: Request) => {
const searchParams = new URL(req.url).searchParams;
return Response.json(Object.fromEntries(searchParams.entries()));
};

You can also get the body of POST requests:

View and run this example on Val Town

export default async function handler(request: Request) {
if (request.method !== "POST") {
return Response.json({ message: "This val responds to POST requests." }, {
status: 400,
});
}
try {
const body = await request.json();
return Response.json(body);
} catch (e) {
return Response.json({ message: "The body of this request was not JSON-encoded." }, {
status: 400,
});
}
}

To obtain the HTTP endpoint, use the “Copy HTTP endpoint” button in the … menu.