Skip to content

ShokupanContext

Defined in: src/context.ts:126

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> = Record<string, any>

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:219

any

Server<any>

State

Shokupan

AbortSignal

boolean = false

string

ShokupanContext<State, Params>

optional [$debug]: DebugCollector

Defined in: src/context.ts:135


optional [$finalResponse]: Response

Defined in: src/context.ts:136


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

Defined in: src/context.ts:137


[$routeMatched]: boolean = false

Defined in: src/context.ts:153


readonly optional app: Shokupan

Defined in: src/context.ts:223


handlerStack: HandlerStackItem[] = []

Defined in: src/context.ts:132


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:410


params: Params

Defined in: src/context.ts:130


readonly request: any

Defined in: src/context.ts:220


readonly response: ShokupanResponse

Defined in: src/context.ts:134


readonly optional server: Server<any>

Defined in: src/context.ts:221


session: SessionData & object

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

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:299


sessionStore: Store

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


readonly optional signal: AbortSignal

Defined in: src/context.ts:224


state: State

Defined in: src/context.ts:131

get cookies(): Record<string, string>

Defined in: src/context.ts:316

Request cookies

Record<string, string>


get headers(): any

Defined in: src/context.ts:367

Request headers

any


get host(): string

Defined in: src/context.ts:341

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

string


get hostname(): string

Defined in: src/context.ts:334

Request hostname (e.g. “localhost”)

string


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

Defined in: src/context.ts:398

Socket.io server

Server<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, any>


get ip(): SocketAddress

Defined in: src/context.ts:329

Client IP address

SocketAddress


get logger(): Logger

Defined in: src/context.ts:142

Application logger instance

Logger


get method(): any

Defined in: src/context.ts:264

HTTP method

any


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

Defined in: src/context.ts:709

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>>


get origin(): string

Defined in: src/context.ts:360

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

string


get path(): any

Defined in: src/context.ts:268

Request path

any


get protocol(): string

Defined in: src/context.ts:348

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

string


get query(): Record<string, any>

Defined in: src/context.ts:303

Request query params

Record<string, any>


get req(): any

Defined in: src/context.ts:260

Base request

any


get requestId(): string

Defined in: src/context.ts:194

string


get res(): ShokupanResponse

Defined in: src/context.ts:378

Base response object

ShokupanResponse


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

Defined in: src/context.ts:383

Get the raw response body content (if available)

string | ArrayBuffer | Uint8Array<ArrayBufferLike>


get secure(): boolean

Defined in: src/context.ts:355

Whether request is secure (https)

boolean


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

Defined in: src/context.ts:393

Socket.io socket

Socket<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, any>


get url(): URL

Defined in: src/context.ts:248

URL


get ws(): ServerWebSocket<undefined>

Defined in: src/context.ts:388

Raw WebSocket connection

ServerWebSocket<undefined>

body<T>(): Promise<T>

Defined in: src/context.ts:672

Read request body with caching to avoid double parsing. The body is only parsed once and cached for subsequent reads.

T = any

Promise<T>


emit(event, data?): void

Defined in: src/context.ts:843

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:993

Respond with a file

string

BlobPropertyBag

ResponseInit

Promise<Response>


get(name): any

Defined in: src/context.ts:373

Get a request header

string

Header name

any


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

Defined in: src/context.ts:922

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:854

Respond with a JSON object

object | Promise<object>

number

HeadersInit

Promise<Response>


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

Defined in: src/context.ts:1028

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:700

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:170

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:718

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:1048

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:944

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:766

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:820

Send a response

BodyInit

Response body

ResponseInit

Response options

Response

Response


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

Defined in: src/context.ts:405

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:590

Set a cookie

string

Cookie name

string

Cookie value

CookieOptions = {}

Cookie options

ShokupanContext<State, Params>


setRenderer(renderer): void

Defined in: src/context.ts:189

JSXRenderer

void


status(statusCode): Promise<Response>

Defined in: src/context.ts:977

Respond with a status code DOES NOT CHAIN!

number | Promise<number>

Promise<Response>


stream(callback, onError?): Response

Defined in: src/context.ts:1131

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:1209

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:1172

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:891

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:432

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")
});
});