masterRequest
API reference for the masterRequest class used in plugin hooks.
Overview
The masterRequest class manages HTTP request/response lifecycle.
masterRequest is passed to all router plugin hooks and provides methods for reading requests, setting responses, managing cookies, and injecting global values.
Properties
Read-only and mutable properties.
request: RequestThe original Bun Request object
URL: URLParsed URL object
response: Response | undefinedCurrent response (after_request only)
isAskingHTML: booleanTrue if Accept header includes text/html
isStaticAsset: booleanTrue if request is for static file
currentState: RequestState"before_request" | "request" | "after_request"
serverInstance: Bun.ServerThe Bun server instance
Response Methods
Methods for setting and managing responses.
setResponse(body, init?)
Set the response body and options.
setResponse(body: BodyInit | null, init?: ResponseInit): this
// Set JSON responsemaster.setResponse(JSON.stringify({ success: true }),{ headers: { "Content-Type": "application/json" } });// Set HTML responsemaster.setResponse("<h1>Hello</h1>", {headers: { "Content-Type": "text/html" },});
request state. Throws if response already set.isResponseSetted()
Check if response has been set.
if (!master.isResponseSetted()) {master.setResponse("Default response");}
unsetResponse()
Clear the current response.
// Override previous plugin's responsemaster.unsetResponse();master.setResponse("New response");
sendNow()
Skip remaining request plugins and send immediately.
// Immediately send response, skip other request pluginsmaster.setResponse("Immediate!");master.sendNow();
setHeader(name, value)
Set a response header.
master.setHeader("X-Custom-Header", "value");master.setHeader("Cache-Control", "no-cache");
Context Methods
Share data between plugin hooks.
setContext(context)
Set context data (merges with existing).
// In before_requestmaster.setContext({ userId: "123", role: "admin" });// Later, add more contextmaster.setContext({ timestamp: Date.now() });
getContext<T>()
Get context data with type.
type MyContext = { userId: string; role: string };const ctx = master.getContext<MyContext>();console.log(ctx.userId); // "123"
Cookie Methods
Read and write cookies.
setCookie(name, data, options?)
Set a cookie on the response.
setCookie<T extends Record<string, unknown>>(name: string,data: T,options?: CookieOptions): thistype CookieOptions = {encrypted?: boolean; // Encrypt cookie valuehttpOnly?: boolean;secure?: boolean;sameSite?: "Lax" | "Strict" | "None";maxAge?: number; // Secondspath?: string;domain?: string;};
// Set encrypted session cookiemaster.setCookie("session",{ userId: "123", role: "admin" },{ encrypted: true, httpOnly: true, secure: true });// Set plain cookiemaster.setCookie("preferences", { theme: "dark" });
getCookie<T>(name, encrypted?)
Read a cookie from the request.
// Read encrypted cookieconst session = master.getCookie<{ userId: string }>("session",true // encrypted);if (session) {console.log(session.userId);}
deleteCookie(name, options?)
Delete a cookie.
master.deleteCookie("session", { path: "/" });
Global Values
Inject values accessible client-side.
setGlobalValues(values)
Inject globals into client-side window.
// Declare global typedeclare global {var __USER_DATA__: { name: string } | undefined;}// Inject in pluginmaster.setGlobalValues({__USER_DATA__: { name: "John" },});// Access client-sideconsole.log(globalThis.__USER_DATA__?.name); // "John"
before_request and request states.preventGlobalValuesInjection()
Disable global value injection for this request.
// For API routes, prevent unnecessary injectionif (master.URL.pathname.startsWith("/api")) {master.preventGlobalValuesInjection();}
Utility Methods
Additional helper methods.
preventLog()Disable server logging for this request
preventRewrite()Disable HTML rewrite plugins for this request
isGlobalValuesInjectionPrevented()Check if global injection is disabled
