Skip to content

ShokupanContext

Defined in: src/context.ts:137

Shokupan Request Context

The context object passed to all middleware and route handlers. Provides access to request data, response helpers, and typed state management.

app.get('/hello', (ctx) => {
return ctx.json({ message: 'Hello' });
});
interface AppState {
userId: string;
requestId: string;
}
const app = new Shokupan<AppState>();
app.use((ctx, next) => {
ctx.state.requestId = crypto.randomUUID(); // ✓ Type-safe
return next();
});
app.get('/users/:userId/posts/:postId', (ctx) => {
// ctx.params is automatically typed as { userId: string; postId: string }
const { userId, postId } = ctx.params;
return ctx.json({ userId, postId });
});
interface RequestState {
userId: string;
permissions: string[];
}
const app = new Shokupan<RequestState>();
app.get('/admin/users/:userId', (ctx) => {
// Both typed!
const { userId } = ctx.params; // ✓ From path
const { permissions } = ctx.state; // ✓ From state
if (!permissions.includes('admin')) {
return ctx.json({ error: 'Forbidden' }, 403);
}
return ctx.json({ userId });
});

State extends Record<string, any> = GlobalShokupanState

The shape of ctx.state for type-safe state access across middleware.

Params extends Record<string, string> = Record<string, string>

The shape of ctx.params based on the route path pattern.

new ShokupanContext<State, Params>(request, server?, state?, app?, signal?, enableMiddlewareTracking?, requestId?): ShokupanContext<State, Params>

Defined in: src/context.ts:240

any

Server<any>

State

Shokupan<any>

AbortSignal

boolean = false

string

ShokupanContext<State, Params>

optional [$debug]: DebugCollector

Defined in: src/context.ts:146


optional [$finalResponse]: Response

Defined in: src/context.ts:147


optional [$onWsMessage]: (msg) => void

Defined in: src/context.ts:174

any

void


optional [$rawBody]: string | ArrayBuffer | Uint8Array<ArrayBufferLike>

Defined in: src/context.ts:148


[$routeMatched]: boolean = false

Defined in: src/context.ts:172


optional [$ws]: ServerWebSocket<any>

Defined in: src/context.ts:202


optional [$wsMessages]: any[]

Defined in: src/context.ts:173


readonly optional app: Shokupan<any>

Defined in: src/context.ts:244


handlerStack: HandlerStackItem[] = []

Defined in: src/context.ts:143


isHtmx: boolean

Defined in: src/plugins/application/htmx/index.ts:14

Checks if the request is an HTMX request.


isHtmxBoosted: boolean

Defined in: src/plugins/application/htmx/index.ts:18

Checks if the request is boosting.


isUpgraded: boolean = false

Defined in: src/context.ts:430


optional matchedRoute: ShokupanRoute

Defined in: src/context.ts:175


params: Params

Defined in: src/context.ts:141


readonly request: any

Defined in: src/context.ts:241


readonly optional server: Server<any>

Defined in: src/context.ts:242


session: SessionData & object

Defined in: src/plugins/middleware/session.ts:301

id: string

destroy(): Promise<void>

Promise<void>

regenerate(): Promise<void>

Promise<void>

reload(): Promise<void>

Promise<void>

save(): Promise<void>

Promise<void>

touch(): void

void


sessionID: string

Defined in: src/plugins/middleware/session.ts:302


sessionStore: Store

Defined in: src/plugins/middleware/session.ts:303


readonly optional signal: AbortSignal

Defined in: src/context.ts:245


state: State

Defined in: src/context.ts:142

get cookies(): Record<string, string>

Defined in: src/context.ts:336

Request cookies

Record<string, string>


get headers(): any

Defined in: src/context.ts:387

Request headers

any


get host(): string

Defined in: src/context.ts:361

Request host (e.g. “localhost:3000”)

string


get hostname(): string

Defined in: src/context.ts:354

Request hostname (e.g. “localhost”)

string


get io(): Server<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, any> | undefined

Defined in: src/context.ts:418

Socket.io server

Server<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, any> | undefined


get ip(): SocketAddress | null | undefined

Defined in: src/context.ts:349

Client IP address

SocketAddress | null | undefined


get logger(): Logger | undefined

Defined in: src/context.ts:153

Application logger instance

Logger | undefined


get method(): any

Defined in: src/context.ts:284

HTTP method

any


get nativeStream(): ReadableStream<Uint8Array<ArrayBufferLike>> | null

Defined in: src/context.ts:721

Exposes the raw, unread incoming ReadableStream of the HTTP request body. Use this if you want to manually process chunks (e.g., custom streaming parsers) without anything being buffered to memory or disk first.

ReadableStream<Uint8Array<ArrayBufferLike>> | null


get origin(): string

Defined in: src/context.ts:380

Request origin (e.g. “http://localhost:3000”)

string


get path(): any

Defined in: src/context.ts:288

Request path

any


get protocol(): string

Defined in: src/context.ts:368

Request protocol (e.g. “http:”, “https:“)

string


get query(): Record<string, any>

Defined in: src/context.ts:323

Request query params

Record<string, any>


get req(): any

Defined in: src/context.ts:280

Base request

any


get requestBody(): any

Defined in: src/context.ts:701

Gets the parsed request body if it has been read.

any


get requestId(): string

Defined in: src/context.ts:215

string


get res(): ShokupanResponse

Defined in: src/context.ts:398

Base response object

ShokupanResponse


get response(): ShokupanResponse

Defined in: src/context.ts:160

Response object (lazy-initialized)

ShokupanResponse


get responseBody(): string | ArrayBuffer | Uint8Array<ArrayBufferLike> | undefined

Defined in: src/context.ts:403

Get the raw response body content (if available)

string | ArrayBuffer | Uint8Array<ArrayBufferLike> | undefined


get secure(): boolean

Defined in: src/context.ts:375

Whether request is secure (https)

boolean


get socket(): Socket<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, any> | undefined

Defined in: src/context.ts:413

Socket.io socket

Socket<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, any> | undefined


get url(): URL

Defined in: src/context.ts:268

URL


get ws(): ServerWebSocket<any> | undefined

Defined in: src/context.ts:408

Raw WebSocket connection

ServerWebSocket<any> | undefined

body<T>(): Promise<T>

Defined in: src/context.ts:677

T = any

Promise<T>


emit(event, data?): void

Defined in: src/context.ts:854

Emit an event to the client (WebSocket only)

string

Event name

any

Event data (Must be JSON serializable)

void


file(path, fileOptions?, responseOptions?): Promise<Response>

Defined in: src/context.ts:1007

Respond with a file

string

BlobPropertyBag

ResponseInit

Promise<Response>


get(name): any

Defined in: src/context.ts:393

Get a request header

string

Header name

any


html(html, status?, headers?): Promise<Response>

Defined in: src/context.ts:933

Respond with HTML content

string | Promise<string>

number

HeadersInit

Promise<Response>


htmxRedirect(url): void

Defined in: src/plugins/application/htmx/index.ts:30

Sets the HX-Redirect header.

string

void


json(data, status?, headers?): Promise<Response>

Defined in: src/context.ts:865

Respond with a JSON object

object | Promise<object>

number

HeadersInit

Promise<Response>


jsx(element, args?, status?, headers?): Promise<Response>

Defined in: src/context.ts:1069

Render a JSX element

any

JSX Element

unknown

JSX Element Args/Props

number

HTTP Status

HeadersInit

HTTP Headers

Promise<Response>


nativeFormData(): Promise<FormData>

Defined in: src/context.ts:712

Bypasses the configured maxBodySize and memory buffering, directly invoking the underlying native runtime’s FormData parser.

In Bun, this handles large files by seamlessly backing them up to disk, keeping memory usage extremely low. Use this when handling large file uploads.

Promise<FormData>


onSocketDisconnect(callback): void

Defined in: src/context.ts:191

Registers a callback to be executed when the associated WebSocket disconnects. This is only applicable for requests that are part of a WebSocket interaction or upgrade.

() => void | Promise<void>

void


parseBody(): Promise<void>

Defined in: src/context.ts:730

Pre-parse the request body before handler execution. This improves performance and enables Node.js compatibility for large payloads. Errors are deferred until the body is actually accessed in the handler.

Promise<void>


pipe(stream, options?): Response

Defined in: src/context.ts:1089

Pipe a ReadableStream to the response

ReadableStream

ReadableStream to pipe

ResponseInit

Response options (status, headers)

Response


pushUrl(url): void

Defined in: src/plugins/application/htmx/index.ts:26

Sets the HX-Push-Url header.

string | false

void


redirect(url, status): Promise<Response>

Defined in: src/context.ts:955

Respond with a redirect

string | Promise<string>

number = 302

Promise<Response>


refresh(): void

Defined in: src/plugins/application/htmx/index.ts:34

Sets the HX-Refresh header.

void


respond(data, status?, headers?): Promise<Response>

Defined in: src/context.ts:778

Respond with automatic content negotiation Uses Accept header to determine the best response format

any

Data to respond with

number

HTTP status code

HeadersInit

Additional headers

Promise<Response>


send(body?, options?): Response

Defined in: src/context.ts:832

Send a response

BodyInit

Response body

ResponseInit

Response options

Response

Response


set(key, value): ShokupanContext<State, Params>

Defined in: src/context.ts:425

Helper to set a header on the response

string

Header key

string

Header value

ShokupanContext<State, Params>


setCookie(name, value, options): ShokupanContext<State, Params>

Defined in: src/context.ts:603

Set a cookie

string

Cookie name

string

Cookie value

CookieOptions = {}

Cookie options

ShokupanContext<State, Params>


setRenderer(renderer): void

Defined in: src/context.ts:210

JSXRenderer

void


status(statusCode): Promise<Response>

Defined in: src/context.ts:991

Respond with a status code DOES NOT CHAIN!

number | Promise<number>

Promise<Response>


stream(callback, onError?): Response

Defined in: src/context.ts:1246

Generic streaming helper for binary/text data

(stream) => void | Promise<void>

Callback function that receives a StreamHelper

StreamErrorHandler

Optional error handler

Response


streamSSE(callback, onError?): Response

Defined in: src/context.ts:1324

Server-Sent Events (SSE) streaming helper

(stream) => void | Promise<void>

Callback function that receives an SSEStreamHelper

SSEStreamErrorHandler

Optional error handler

Response


streamText(callback, onError?): Response

Defined in: src/context.ts:1287

Text streaming helper with proper headers

(stream) => void | Promise<void>

Callback function that receives a TextStreamHelper

TextStreamErrorHandler

Optional error handler

Response


text(data, status?, headers?): Promise<Response>

Defined in: src/context.ts:902

Respond with a text string

string | Promise<string>

number

HeadersInit

Promise<Response>


trigger(event, options?): void

Defined in: src/plugins/application/htmx/index.ts:22

Sets the HX-Trigger header.

string | Record<string, any>

"receive" | "settle" | "swap"

void


upgrade(options?): boolean

Defined in: src/context.ts:452

Upgrades the request to a WebSocket connection.

Upgrade options or inline WebSocket handlers

[Request, ...options: ([State] extends [undefined] ? [options?: { data?: undefined; headers?: HeadersInit }] : [options: { data: State; headers?: HeadersInit }])[]][1] | InlineWebSocketHandlers<State> & object

boolean

true if upgraded, false otherwise

This method will link the WebSocket connection to the context object, allowing you to access the connection in your handlers.

app.get('/ws', (ctx) => {
ctx.upgrade({
open: (ctx, ws) => ws.send("Connected"),
message: (ctx, ws, msg) => ws.send(msg),
close: (ctx, ws) => console.log("Disconnected")
});
});