Requests
Route handlers receive a RequestFacade object
that bundles everything you need to handle an incoming HTTP request: body
readers, path parameters, query parameters, cookies, headers, the original
WHATWG Request, and a URL helper. This page walks through each part and shows
how to access and validate it.
For exact member signatures, return types, and errors, see the
primate/request API reference.
| Property | Type | Description |
|---|---|---|
| body | RequestBody |
on-demand body readers |
| path | RequestBag |
path parameters |
| query | RequestBag |
query parameters |
| headers | RequestBag |
request headers |
| cookies | RequestBag |
request cookies (case-sensitive) |
| original | Request |
original WHATWG Request object |
| url | URL |
original request URL |
| forward | (to: string) => Promise<Response> |
forward the request |
RequestFacade also supports a request context store for sharing derived
values between hooks and route handlers (see
Request context).Body
The request body carries data sent to a route, such as JSON, form fields, or a file upload.
In TypeScript and JavaScript, choose how to read it:
- Read and validate manually. Choose a
request.bodyreader that matches the incomingContent-Type. The reader checks the header before reading and decodes the body on demand. You can pass the decoded value to a schema, as in the TypeScript example below. - Declare the media type and schema. With
route.with(), Primate checkscontentTypebefore calling the handler. It does not read the body at that point. Calling the matching reader decodes the body and applies the optionalbodyschema. - Use the original request. For native APIs such as
request.original.formData(), read fromrequest.originalinstead. This consumes the same stream but bypasses Primate's reader limits and schema validation.
import p from "pema";
import route from "primate/route";
const BodySchema = p({ name: p.string.min(1) });
export default route({
async post(request) {
const { name } = BodySchema.parse(await request.body.json());
return `Hello, ${name}`;
},
});package main
import (
"fmt"
"primate.run/go/route"
)
var _ = route.Post(func(request route.Request) any {
json, err := request.Body.JSON()
if err != nil {
return map[string]any{"error": err.Error()}
}
name, _ := json["name"].(string)
return fmt.Sprintf("Hello, %s", name)
})package routes.identify
import run.primate.Route
fun main() {
Route.post("text/plain") { request ->
val name = request.bodyText()
"Hello, $name"
}
}from primate import Response, Route
@Route.post(content_type="application/json")
def identify(request):
body = request.body.json()
name = body.get("name") if isinstance(body, dict) else None
if not isinstance(name, str) or not name:
return Response.text("Name is required", {"status": 400})
return f"Hello, {name}"require 'primate/response'
require 'primate/route'
Route.post(content_type: 'application/json') do |request|
body = request.body.json
name = body['name'] if body.is_a?(Hash)
if name.is_a?(String) && !name.empty?
"Hello, #{name}"
else
Response.text('Name is required', status: 400)
end
endThe examples respond with 200 OK and Hello, John when you POST to
/identify. For the JSON examples, send {"name": "John"} with
Content-Type: application/json. The Kotlin SDK uses bodyText() instead:
send John as the body with Content-Type: text/plain.
To have the JSON reader validate the body instead of calling the schema
manually, declare it in route.with():
import p from "pema";
import route from "primate/route";
const BodySchema = p({ name: p.string.min(1) });
export default route({
post: route.with({
contentType: "application/json",
body: BodySchema,
}, async request => {
const { name } = await request.body.json();
return `Hello, ${name}`;
}),
});| Content type | Method |
|---|---|
text/plain |
text() |
application/json |
json() |
application/x-www-form-urlencoded |
form() or formEntries() |
multipart/form-data |
multipart() |
application/octet-stream |
blob() |
form() returns a Dict<string>. If a
field name occurs more than once, the dictionary keeps its last value. Use
formEntries() to preserve every value and the original submission order as
[name, value][]:
const entries = await request.body.formEntries();
const categoryIds = entries
.filter(([name]) => name === "categoryIds")
.map(([, value]) => value);Primate's readers buffer the body, and you can consume it only once. By
default, text, JSON, and URL-encoded form readers are limited to 1 MiB;
multipart and blob readers are limited to 16 MiB for the entire body.
Set limit in route.with() (in bytes) to override the default for one
handler. See HTTP body limits.
Primate returns 413 when a reader exceeds its limit and 415 when
the request's Content-Type is missing or doesn't match the type declared in
route.with(). Each reader also checks the media type it accepts. A mismatch
at that step rejects the read rather than automatically returning 415.
Malformed JSON also rejects the read; handle it in your route if you want to
return 400. A Pema validation failure in a route handler already returns
400. See the RequestBody API reference.
Path
Path parameters extracted from bracketed segments in your route path (e.g.
routes/users/[id], routes/blog/[year]/[slug]).
Use the request's path bag to read them. In TypeScript, a
RequestBag has get(), try(), and has().
import route from "primate/route";
export default route({
get(request) {
// throws if missing
const id = request.path.get("id"); // "42" for /user/42
return `User #${id}`;
},
});package main
import (
"primate.run/go/response"
"primate.run/go/route"
)
var _ = route.Get(func(request route.Request) any {
id, err := request.Path.Get("id")
if err != nil {
return response.Text("Missing id", map[string]any{"status": 400})
}
return "User #" + id
})package routes.user
import run.primate.Route
fun main() {
Route.get { request ->
val id = requireNotNull(request.path["id"])
"User #$id"
}
}from primate import Route
@Route.get
def get(request):
return f"User #{request.path['id']}"require 'primate/route'
Route.get do |request|
"User ##{request.path['id']}"
endFor optional parameters, use a lookup that handles missing values without throwing.
import route from "primate/route";
export default route({
get(request) {
const year = request.path.get("year");
const slug = request.path.try("slug"); // string | undefined
return slug ? `Post ${slug} from ${year}` : `All posts in ${year}`;
},
});package main
import "primate.run/go/route"
var _ = route.Get(func(request route.Request) any {
year := request.Path.Try("year")
if slug := request.Path.Try("slug"); slug != "" {
return "Post " + slug + " from " + year
}
return "All posts in " + year
})package routes.blog
import run.primate.Route
fun main() {
Route.get { request ->
val year = requireNotNull(request.path["year"])
val slug = request.path["slug"]
if (slug == null) "All posts in $year" else "Post $slug from $year"
}
}from primate import Route
@Route.get
def get(request):
year = request.path["year"]
slug = request.path.try_get("slug")
return f"Post {slug} from {year}" if slug else f"All posts in {year}"require 'primate/route'
Route.get do |request|
year = request.path['year']
slug = request.path.try('slug')
slug ? "Post #{slug} from #{year}" : "All posts in #{year}"
end[[slug]] to denote an optional
path segment.In TypeScript, you can validate all parameters at once with a Pema schema.
import p from "pema";
import route from "primate/route";
const PathSchema = p({ id: p.string.regex(/^\d+$/) });
export default route({
get(request) {
const { id } = PathSchema.parse(request.path); // id: string (digits only)
return `User #${id}`;
},
});Query
The query string is split into individual parameters and exposed as a
RequestBag. Use it to read ?page=2&search=john-style parameters. Query
string parameters are matched case-insensitively. If a query parameter appears
multiple times, Primate keeps only the last.
import route from "primate/route";
export default route({
get(request) {
const page = Number(request.query.try("page") ?? "1"); // 1 if missing
const term = request.query.get("search");
return `Searching "${term}" (page ${page})`;
},
});package main
import (
"fmt"
"strconv"
"primate.run/go/route"
)
var _ = route.Get(func(request route.Request) any {
page, err := strconv.Atoi(request.Query.Try("page"))
if err != nil {
page = 1
}
term := request.Query.Try("search")
return fmt.Sprintf("Searching \"%s\" (page %d)", term, page)
})package routes.search
import run.primate.Route
fun main() {
Route.get { request ->
val page = request.query["page"]?.toIntOrNull() ?: 1
val term = request.query["search"] ?: ""
"Searching \"$term\" (page $page)"
}
}from primate import Route
@Route.get
def get(request):
page = request.query.try_get("page") or "1"
term = request.query.get("search")
return f'Searching "{term}" (page {page})'require 'primate/route'
Route.get do |request|
page = request.query.try('page') || '1'
term = request.query['search']
"Searching \"#{term}\" (page #{page})"
endSchema-validate the entire query string:
import p from "pema";
import route from "primate/route";
const QuerySchema = p({
page: p.int.loose.min(1).default(1),
search: p.string.min(1),
});
export default route({
get(request) {
const { page, search } = QuerySchema.parse(request.query);
return `Searching "${search}" (page ${page})`;
},
});request.query normalizes keys, request.url.searchParams does not.Headers
Request headers as a RequestBag. Header keys are matched case-insensitively.
Values use the runtime's WHATWG Headers normalization.
import route from "primate/route";
export default route({
get(request) {
const ua = request.headers.try("user-agent"); // may be undefined
const contentType = request.headers.try("content-type");
// returned as JSON
return { ua, contentType };
},
});package main
import "primate.run/go/route"
var _ = route.Get(func(request route.Request) any {
return map[string]string{
"ua": request.Headers.Try("user-agent"),
"contentType": request.Headers.Try("content-type"),
}
})package routes.headers
import run.primate.Route
fun main() {
Route.get { request ->
mapOf(
"ua" to request.headers["user-agent"],
"contentType" to request.headers["content-type"],
)
}
}from primate import Route
@Route.get
def get(request):
return {
"ua": request.headers.try_get("user-agent"),
"contentType": request.headers.try_get("content-type"),
}require 'primate/route'
Route.get do |request|
{
ua: request.headers.try('user-agent'),
contentType: request.headers.try('content-type')
}
endIn TypeScript, you can validate or transform headers with a Pema schema.
import http from "@rcompat/http";
import p from "pema";
import route from "primate/route";
const HeadersSchema = p({
"content-type": p.string.optional(),
authorization: p.string.startsWith("Bearer ").optional(),
});
export default route({
get(request) {
const headers = HeadersSchema.parse(request.headers);
const token = headers.authorization?.slice("Bearer ".length);
const status = token ? http.Status.NO_CONTENT : http.Status.UNAUTHORIZED;
return new Response(null, { status });
},
});
Cookies
Request cookies as a RequestBag. Cookie names are case-sensitive (unlike
other request bags). If a cookie repeats, Primate keeps the last value.
import http from "@rcompat/http";
import response from "primate/response";
import route from "primate/route";
export default route({
get(request) {
const session = request.cookies.try("session"); // string | undefined
if (!session) {
return response.error({
body: "Unauthorized",
status: http.Status.UNAUTHORIZED,
});
}
return "Hello";
},
});package main
import (
"primate.run/go/response"
"primate.run/go/route"
)
var _ = route.Get(func(request route.Request) any {
if request.Cookies.Try("session") == "" {
return response.Text("Unauthorized", map[string]any{"status": 401})
}
return "Hello"
})package routes.cookies
import run.primate.Response
import run.primate.Route
fun main() {
Route.get { request ->
if (request.cookies["session"].isNullOrEmpty()) {
Response.Text("Unauthorized", mapOf("status" to 401))
} else {
"Hello"
}
}
}from primate import Response, Route
@Route.get
def get(request):
if not request.cookies.try_get("session"):
return Response.text("Unauthorized", {"status": 401})
return "Hello"require 'primate/response'
require 'primate/route'
Route.get do |request|
if request.cookies.try('session').to_s.empty?
Response.text('Unauthorized', status: 401)
else
'Hello'
end
endIn TypeScript, you can validate the whole cookie bag with a Pema schema.
import http from "@rcompat/http";
import p from "pema";
import response from "primate/response";
import route from "primate/route";
const CookieSchema = p({
session: p.uuid.optional(),
});
export default route({
get(request) {
const { session } = CookieSchema.parse(request.cookies);
return response.text(session ? "OK" : "No session", {
status: session ? http.Status.OK : http.Status.FORBIDDEN,
});
},
});
Original
The original WHATWG Request object as received from the runtime. Use this for
low-level capabilities like clone(), signal, or direct header access when
needed.
import route from "primate/route";
export default route({
get(request) {
// Abort handling if the client disconnects
request.original.signal.addEventListener("abort", () => {
console.log("client disconnected");
});
// Access a raw header
const lang = request.original.headers.get("Accept-Language");
return new Response(lang ?? "en-US");
},
});
URL
In TypeScript, request.url is a WHATWG URL you can use to resolve relative
URLs or read searchParams. The Wasm examples show how to read the pathname
exposed by each SDK.
import route from "primate/route";
export default route({
get(request) {
const url = request.url;
// prefer request.query over url.searchParams
const page = url.searchParams.get("page") ?? "1";
// build a new URL relative to the request
const cdn = new URL("/assets/logo.svg", url);
// returned as JSON
return { page, cdn: cdn.href };
},
});package main
import "primate.run/go/route"
var _ = route.Get(func(request route.Request) any {
return request.Url.Pathname
})package routes.url
import run.primate.Route
fun main() {
Route.get { request -> request.pathname }
}from primate import Route
@Route.get
def get(request):
return request.url.pathnamerequire 'primate/route'
Route.get do |request|
request.url.pathname
endForward
request.forward() sends the original method and body stream to an upstream
URL. Forward before consuming the body with request.body or
request.original. No body-parsing setting needs to be disabled.
Only the original Content-Type header is forwarded automatically. You can
explicitly supply additional headers.
import route from "primate/route";
export default route({
get(request) {
return request.forward("https://upstream.internal/service", {
Authorization: request.headers.try("authorization") ?? "",
Accept: request.headers.try("accept") ?? "",
});
},
});Use this to implement simple reverse proxies, edge routing, or fan-out/fan-in patterns.
Request context
RequestFacade includes a request context store: request-scoped values that
hooks can attach for downstream hooks and route handlers to read.
Use request context for derived server values (e.g. authenticated user,
locale, feature flags, request IDs). For client input, use body, path,
query, headers, or cookies.
Context is most commonly set in hooks.
Request context is server-only. It is not included in hydration or client navigation data, so hooks and route handlers can use it for sensitive or non-serializable request-scoped values. Incoming request headers and cookies are likewise server-only.
API
| Method | Description |
|---|---|
request.context.set(key, value) |
Set a context value |
request.context.set<T>(key, fn) |
Update a context value with a function |
request.context.get<T>(key) |
Get a context value (throws if missing) |
request.context.try<T>(key) |
Get a context value or undefined |
request.context.has(key) |
Check if a context key exists |
request.context.delete(key) |
Remove a context key |
Request. request.forward()
forwards the original request, not your attached context.You can use hooks to authenticate in a hook, and then use in a route.
// routes/+hook.ts
import route from "primate/route";
export default route.hook(async (request, next) => {
const user = await authenticate(request);
request.context.set("auth.user", user);
return next(request);
});