before and after
Two special functions that run around every HTTP function — for authentication, logging, shared validation and response headers.
Name a function before or after and it runs around every HTTP function of the same language. They are never exposed themselves: no URL, MCP tool or schedule.
To protect your API with API keys you don't need code: use the built-in API keys. Use before for other schemes — JWTs, HMAC signatures, basic auth or keys from another system.
#before
Runs ahead of the function. Return nothing to continue, or a response to stop the call. Fields you set on req reach the function.
import { config } from 'wisp';
export async function handler(req) {
if (req.caller) return; // calls from this project's own code, schedules and the console
const token = req.headers.authorization?.replace(/^Bearer /, '');
if (token !== config.require('ADMIN_TOKEN')) {
return { status: 401, body: { error: 'Unauthorized' } };
}
req.user = { role: 'admin' }; // the function sees req.user
}from wisp import config
def handler(req):
if req.get("caller"):
return None
token = req["headers"].get("authorization", "").removeprefix("Bearer ")
if token != config.require("ADMIN_TOKEN"):
return {"status": 401, "body": {"error": "Unauthorized"}}
req["user"] = {"role": "admin"}#after
Runs once the function answered, with the response as { status, headers, body }. Return a changed response, or nothing to keep it.
export async function handler(req, res) {
return { ...res, headers: { ...res.headers, 'x-powered-by': 'my-api' } };
}#Skip them
Public functions such as /health, /login or a webhook receiver can skip both: turn off Run before and after in the function's settings, or untick it in the before/after settings. Functions with HTTP off never run them.
Ask the assistant — "require a bearer token on every function except /health" — and it writes before and sets this up for you.