Serve HTTP routes
Give a handler a method and a path of your own, so any HTTP client can call it.
A handler is called at POST <LUNA_URL>/<Type>/<key>/<handler>, with its args as a JSON body. A payment provider, an OAuth client or an HTML form calls a fixed URL with its own method and body, and cannot send that shape.
A route gives a handler an address of your choosing. The handler keeps its name, so apps and other lunas call it as before.
Give a handler a route
Add route to a handler’s spec, with a method and a path. A path parameter with the name of a key field fills that field.
import { defineLuna, t, table } from "luna";
export const List = defineLuna({
name: "List",
visibility: "public",
key: { id: t.string() },
schema: { items: table({ id: t.id(), text: t.string() }) },
handlers: (h) => ({
add: h(
{ args: { text: t.string() }, route: "POST /lists/:id/items" },
(ctx, { text }) => void ctx.db.items.insert({ text }),
),
all: h({ query: true, route: "GET /lists/:id/items" }, (ctx) => ctx.db.items.find({ orderBy: "id" })),
}),
});
A route takes GET, POST, PUT, PATCH or DELETE. Luna answers HEAD and OPTIONS for every route by itself, and answers 405 with an Allow header for a method the path does not take.
Call a route
Routes are served on a host of their own, apart from LUNA_URL. Once the environment has a route, luna status prints its address after Routes at, shown here as <ROUTES_URL>. A publishable key goes in the luna-key header, or in the key query parameter.
curl -X POST "<ROUTES_URL>/lists/groceries/items" \
-H "luna-key: $LUNA_KEY" \
-H "Content-Type: application/json" \
-d '{"text":"milk"}'
curl "<ROUTES_URL>/lists/groceries/items?key=$LUNA_KEY"
The route host serves routes and nothing else. A handler without a route cannot be reached there, and POST /List/groceries/all answers 404. To serve routes on a name of your own, see Use your own domain.
Write the path
| Segment | Matches |
|---|---|
items |
That exact text |
:item |
One segment, read as item |
* or *path at the end |
The rest of the path, read as rest or path |
When two routes match, text beats a parameter and a parameter beats *, segment by segment from the left. GET /users/me wins over GET /users/:id, and both win over GET /users/*. A deploy refuses two routes with the same method and the same shape of path. An app has at most 1000 routes.
Fill the key and the args
Each key field comes from the path parameter of the same name. A luna type with one key field may name its parameter :key instead. To read a key field from the query or a header, give key with query:<NAME>, header:<NAME> or param:<NAME>.
mine: h({ query: true, route: { path: "GET /mine", key: { id: "header:x-list" } } }, (ctx) => ctx.db.items.count()),
A deploy refuses a route that does not say where each key field comes from. A stateless luna has no key to fill.
Luna fills the args from the body, a JSON object or a URL-encoded form, then the query, then the path parameters left over. When a name comes from more than one place, the path wins over the query and the query over the body. Each value takes its arg’s type, so ?limit=10 fills limit: t.int() and a repeated name fills an array. Args that do not fit are refused with 400 before the luna wakes.
Take the raw request
Give a handler args: t.request() to read the request yourself. It receives a LunaRequest, a web-standard Request with a few additions.
upload: h({ args: t.request(), route: "POST /lists/:id/upload" }, async (ctx, req) => {
const form = await req.form();
for (const text of form.getAll("item")) ctx.db.items.insert({ text: String(text) });
return { from: req.ip, agent: req.headers.get("user-agent") };
}),
| Member | Holds |
|---|---|
params |
The path parameters, by name |
query |
The first value of each query parameter, and searchParams holds them all |
ip |
The client’s address |
form() |
A URL-encoded or multipart body, as FormData |
text(), json(), bytes() |
The body, which you can read more than once |
signal |
Fires when the client goes away |
Headers that start with luna- are taken out. A multipart body needs t.request(), and other handlers answer it with 415. Called by name from an app or another luna, the handler gets its args as a JSON body. A handler with typed args can still read the request as ctx.request.
Answer with a status and headers
A handler that returns a value answers 200 with the value as JSON. Return a web-standard Response to set the status, the headers and the body.
old: h({ route: { path: "GET /l/:id", auth: "none" } }, (ctx) =>
new Response(null, { status: 301, headers: { location: `/lists/${ctx.key.id}/items` } }),
),
Luna drops the headers a handler may not set: those that start with luna- or access-control-, content-length, transfer-encoding, strict-transport-security, alt-svc and the connection’s own headers. Set CORS headers with the cors option below.
An app or a luna that calls the handler by name gets the Response’s body. A status of 400 or more throws an HttpError there, as Errors shows.
Give declared errors a status
A declared error answers 422 by default. The route’s errors gives a code a status of its own, from 400 to 599.
remove: h(
{ args: { item: t.int() }, errors: { NoItem: t.json() }, route: { path: "DELETE /lists/:id/items/:item", errors: { NoItem: 404 } } },
(ctx, { item }) => {
if (!ctx.db.items.get(item)) ctx.fail("NoItem");
ctx.db.items.delete({ where: { id: item } });
},
),
{"error":{"code":"NoItem","data":null}}
Choose who may call
auth |
Who may call | Default for |
|---|---|---|
"publishable" |
A caller with a publishable key or a secret token | A public luna type |
"token" |
A caller with a secret token, as Authorization: Bearer |
A private luna type |
"none" |
Anyone. The handler checks the request itself |
A secret token is accepted on every route. A route refuses a missing credential with 401. Routes skip onBeforeConnect, so a route with "none" checks its caller in the handler, as Check who is calling shows. The keys and tokens are in Keys and tokens.
Let other sites and limits in
cors names the web origins whose pages may read the answers. rateLimit refuses requests past a limit with 429 and a Retry-After header.
route: {
path: "POST /lists/:id/items",
cors: { origins: ["https://app.example.com"] },
rateLimit: { limit: 10, window: "1m", per: "ip" },
},
| Option | Does |
|---|---|
cors.origins |
The origins allowed, or "*" for any |
cors.credentials |
Lets the browser send cookies and Authorization. Not with "*" |
cors.headers, cors.exposeHeaders |
The request headers a page may send, and the answer headers it may read |
cors.maxAge |
How long a browser keeps a preflight answer, 600 seconds by default |
rateLimit.per |
Counts by "ip", the default, or by "credential" |
rateLimit.window |
The window, at most a day |
A route reads a body of at most 10 MiB and answers 413 past it. A call through a route has 60 seconds to answer.
Next steps
- Stream a response sends events while a handler runs.
- Receive webhooks checks a signed request and does the work later.
- Read a tenant’s API lists every route in an OpenAPI document.