Build
Requests and responses
What your handler receives, what it can return, and how JSON, text, HTML, binary data and headers are handled.
#The request
export async function handler(req) {
req.method // "POST"
req.path // "/orders/1042"
req.subpath // "/1042"
req.query // { expand: "items" }
req.headers // lower-case keys: { "content-type": "application/json", ... }
req.body // parsed JSON, raw text, or null
req.rawBody // the body as received (base64 when req.isBase64Encoded)
req.mode // "live" or "test"
req.ip // the caller's IP address
}Two fields appear only in some requests:
req.apiKey—{ id, name }when the project requires API keys.req.caller—{ projectId, kind }when your project's code, a schedule, the MCP server or the console called this one.
#The response
Return an object with status, optional headers and body:
return { status: 201, headers: { location: '/orders/1043' }, body: { id: 1043 } };body is | Sent as |
|---|---|
| Object or array | JSON, with content-type: application/json |
| String | Text. Set content-type for HTML, CSV or XML. |
Bytes (Buffer, bytes) | Binary. Set content-type, for example image/png. |
| Omitted | Empty body |
#Common patterns
#Validate input
export async function handler(req) {
const { email } = req.body ?? {};
if (typeof email !== 'string' || !email.includes('@')) {
return { status: 400, body: { error: 'email is required' } };
}
// ...
}#Serve HTML
def handler(req):
return {"status": 200, "headers": {"content-type": "text/html"}, "body": "<h1>Hello</h1>"}#Redirect
return { status: 302, headers: { location: 'https://example.com/thanks' } };#Accept a file upload
Send the file as the raw request body and read req.rawBody. When req.isBase64Encoded is true, decode it first, then save it with file.write.
#Test or live
req.mode is "test" when the request used ?test. Use it to skip side effects such as sending real emails while you test — but remember drafts and live share the same storage.