API โ€บ @builder.io/qwik-city/middleware/request-handler

AbortMessage

export declare class AbortMessage

Edit this section

append

Appends a Response cookie header using the Set-Cookie header.

The difference between set() and append() is that if the specified header already exists, set() will overwrite the existing value with the new one, whereas append() will append the new value onto the end of the set of values.

append(name: string, value: string | number | Record<string, any>, options?: CookieOptions): void;

Parameter

Type

Description

name

string

value

string | number | Record<string, any>

options

CookieOptions

(Optional)

void

CacheControl

export type CacheControl =
  | CacheControlOptions
  | number
  | "day"
  | "week"
  | "month"
  | "year"
  | "no-cache"
  | "immutable"
  | "private";

Edit this section

ClientConn

export interface ClientConn

Property

Modifiers

Type

Description

country?

string

(Optional)

ip?

string

(Optional)

Edit this section

export interface Cookie

Method

Description

append(name, value, options)

Appends a Response cookie header using the Set-Cookie header.

The difference between set() and append() is that if the specified header already exists, set() will overwrite the existing value with the new one, whereas append() will append the new value onto the end of the set of values.

delete(name, options)

Deletes cookie value by name using the Response cookie header.

get(name)

Gets a Request cookie header value by name.

getAll()

Gets all Request cookie headers.

has(name)

Checks if the Request cookie header name exists.

headers()

Returns an array of all the set Response Set-Cookie header values.

set(name, value, options)

Sets a Response cookie header using the Set-Cookie header.

Edit this section

CookieOptions

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie

export interface CookieOptions

Property

Modifiers

Type

Description

domain?

string

(Optional) Defines the host to which the cookie will be sent. If omitted, this attribute defaults to the host of the current document URL, not including subdomains.

expires?

Date | string

(Optional) Indicates the maximum lifetime of the cookie as an HTTP-date timestamp. If both expires and maxAge are set, maxAge has precedence.

httpOnly?

boolean

(Optional) Forbids JavaScript from accessing the cookie, for example, through the document.cookie property.

maxAge?

number | [number, 'seconds' | 'minutes' | 'hours' | 'days' | 'weeks']

(Optional) Indicates the number of seconds until the cookie expires. A zero or negative number will expire the cookie immediately. If both expires and maxAge are set, maxAge has precedence. You can also use the array syntax to set the max-age using minutes, hours, days or weeks. For example, { maxAge: [3, "days"] } would set the cookie to expire in 3 days.

path?

string

(Optional) Indicates the path that must exist in the requested URL for the browser to send the Cookie header.

sameSite?

'strict' | 'lax' | 'none' | 'Strict' | 'Lax' | 'None' | boolean

(Optional) Controls whether or not a cookie is sent with cross-site requests, providing some protection against cross-site request forgery attacks (CSRF).

secure?

boolean

(Optional) Indicates that the cookie is sent to the server only when a request is made with the https: scheme (except on localhost)

Edit this section

CookieValue

export interface CookieValue

Property

Modifiers

Type

Description

json

<T = unknown>() => T

number

() => number

value

string

Edit this section

data

data: T;

DeferReturn

export type DeferReturn<T> = () => Promise<T>;

Edit this section

delete

Deletes cookie value by name using the Response cookie header.

delete(name: string, options?: Pick<CookieOptions, 'path' | 'domain' | 'sameSite'>): void;

Parameter

Type

Description

name

string

options

Pick<CookieOptions, 'path' | 'domain' | 'sameSite'>

(Optional)

void

EnvGetter

export interface EnvGetter

Method

Description

get(key)

Edit this section

get

Gets a Request cookie header value by name.

get(name: string): CookieValue | null;

Parameter

Type

Description

name

string

CookieValue | null

getAll

Gets all Request cookie headers.

getAll(): Record<string, CookieValue>;

Returns:

Record<string, CookieValue>

getErrorHtml

export declare function getErrorHtml(status: number, e: any): string;

Parameter

Type

Description

status

number

e

any

string

Edit this section

has

Checks if the Request cookie header name exists.

has(name: string): boolean;

Parameter

Type

Description

name

string

boolean

headers

Returns an array of all the set Response Set-Cookie header values.

headers(): string[];

Returns:

string[]

mergeHeadersCookies

mergeHeadersCookies: (headers: Headers, cookies: CookieInterface) => Headers;

Parameter

Type

Description

headers

Headers

cookies

CookieInterface

Headers

Edit this section

RedirectMessage

export declare class RedirectMessage extends AbortMessage

Extends: AbortMessage

Edit this section

RequestEvent

export interface RequestEvent<PLATFORM = QwikCityPlatform> extends RequestEventCommon<PLATFORM>

Extends: RequestEventCommon<PLATFORM>

Property

Modifiers

Type

Description

exited

readonly

boolean

True if the middleware chain has finished executing.

getWritableStream

readonly

() => WritableStream<Uint8Array>

Low-level access to write to the HTTP response stream. Once getWritableStream() is called, the status and headers can no longer be modified and will be sent over the network.

headersSent

readonly

boolean

True if headers have been sent, preventing any more headers from being set.

next

readonly

() => Promise<void>

Invoke the next middleware function in the chain.

NOTE: Ensure that the call to next() is awaited.

Edit this section

RequestEventAction

export interface RequestEventAction<PLATFORM = QwikCityPlatform> extends RequestEventCommon<PLATFORM>

Extends: RequestEventCommon<PLATFORM>

Property

Modifiers

Type

Description

fail

<T extends Record<string, any>>(status: number, returnData: T) => FailReturn<T>

Edit this section

RequestEventBase

export interface RequestEventBase<PLATFORM = QwikCityPlatform>

Property

Modifiers

Type

Description

basePathname

readonly

string

The base pathname of the request, which can be configured at build time. Defaults to /.

cacheControl

readonly

(cacheControl: CacheControl, target?: CacheControlTarget) => void

Convenience method to set the Cache-Control header. Depending on your CDN, you may want to add another cacheControl with the second argument set to CDN-Cache-Control or any other value (we provide the most common values for auto-complete, but you can use any string you want).

See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control and https://qwik.dev/docs/caching/#CDN-Cache-Controls for more information.

clientConn

readonly

ClientConn

Provides information about the client connection, such as the IP address and the country the request originated from.

cookie

readonly

Cookie

HTTP request and response cookie. Use the get() method to retrieve a request cookie value. Use the set() method to set a response cookie value.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies

env

readonly

EnvGetter

Platform provided environment variables.

headers

readonly

Headers

HTTP response headers. Notice it will be empty until you first add a header. If you want to read the request headers, use request.headers instead.

https://developer.mozilla.org/en-US/docs/Glossary/Response\_header

method

readonly

string

HTTP request method.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

params

readonly

Readonly<Record<string, string>>

URL path params which have been parsed from the current url pathname segments. Use query to instead retrieve the query string search params.

parseBody

readonly

() => Promise<unknown>

This method will check the request headers for a Content-Type header and parse the body accordingly. It supports application/json, application/x-www-form-urlencoded, and multipart/form-data content types.

If the Content-Type header is not set, it will return null.

pathname

readonly

string

URL pathname. Does not include the protocol, domain, query string (search params) or hash.

https://developer.mozilla.org/en-US/docs/Web/API/URL/pathname

platform

readonly

PLATFORM

Platform specific data and functions

query

readonly

URLSearchParams

URL Query Strings (URL Search Params). Use params to instead retrieve the route params found in the url pathname.

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

request

readonly

Request

HTTP request information.

sharedMap

readonly

Map<string, any>

Shared Map across all the request handlers. Every HTTP request will get a new instance of the shared map. The shared map is useful for sharing data between request handlers.

signal

readonly

AbortSignal

Request's AbortSignal (same as request.signal). This signal indicates that the request has been aborted.

url

readonly

URL

HTTP request URL.

Edit this section

RequestEventCommon

export interface RequestEventCommon<PLATFORM = QwikCityPlatform> extends RequestEventBase<PLATFORM>

Extends: RequestEventBase<PLATFORM>

Property

Modifiers

Type

Description

error

readonly

(statusCode: ErrorCodes, message: string) => ErrorResponse

When called, the response will immediately end with the given status code. This could be useful to end a response with 404, and use the 404 handler in the routes directory. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Status for which status code should be used.

exit

readonly

() => AbortMessage

html

readonly

(statusCode: StatusCodes, html: string) => AbortMessage

Convenience method to send an HTML body response. The response will be automatically set the Content-Type header totext/html; charset=utf-8. An html() response can only be called once.

json

readonly

(statusCode: StatusCodes, data: any) => AbortMessage

Convenience method to JSON stringify the data and send it in the response. The response will be automatically set the Content-Type header to application/json; charset=utf-8. A json() response can only be called once.

locale

readonly

(local?: string) => string

Which locale the content is in.

The locale value can be retrieved from selected methods using getLocale():

redirect

readonly

(statusCode: RedirectCode, url: string) => RedirectMessage

URL to redirect to. When called, the response will immediately end with the correct redirect status and headers.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections

send

readonly

SendMethod

Send a body response. The Content-Type response header is not automatically set when using send() and must be set manually. A send() response can only be called once.

status

readonly

(statusCode?: StatusCodes) => number

HTTP response status code. Sets the status code when called with an argument. Always returns the status code, so calling status() without an argument will can be used to return the current status code.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

text

readonly

(statusCode: StatusCodes, text: string) => AbortMessage

Convenience method to send an text body response. The response will be automatically set the Content-Type header totext/plain; charset=utf-8. An text() response can only be called once.

Edit this section

RequestEventLoader

export interface RequestEventLoader<PLATFORM = QwikCityPlatform> extends RequestEventAction<PLATFORM>

Extends: RequestEventAction<PLATFORM>

Property

Modifiers

Type

Description

defer

<T>(returnData: Promise<T> | (() => Promise<T>)) => DeferReturn<T>

resolveValue

ResolveValue

Edit this section

requestHandler

export type RequestHandler<PLATFORM = QwikCityPlatform> = (
  ev: RequestEvent<PLATFORM>,
) => Promise<void> | void;

References: RequestEvent

Edit this section

RequestHandler

export type RequestHandler<PLATFORM = QwikCityPlatform> = (
  ev: RequestEvent<PLATFORM>,
) => Promise<void> | void;

References: RequestEvent

Edit this section

ResolveSyncValue

export interface ResolveSyncValue

Edit this section

ResolveValue

export interface ResolveValue

Edit this section

ServerError

export declare class ServerError<T = Record<any, any>> extends Error

Extends: Error

Constructor

Modifiers

Description

(constructor)(status, data)

Constructs a new instance of the ServerError class

Property

Modifiers

Type

Description

data

T

status

number

Edit this section

ServerRenderOptions

export interface ServerRenderOptions extends RenderOptions

Extends: RenderOptions

Property

Modifiers

Type

Description

checkOrigin?

boolean

(Optional) Protection against cross-site request forgery (CSRF) attacks.

When true, for every incoming POST, PUT, PATCH, or DELETE form submissions, the request origin is checked to match the server's origin.

Be careful when disabling this option as it may lead to CSRF attacks.

Defaults to true.

qwikCityPlan

QwikCityPlan

render

Render

Edit this section

ServerRequestEvent

Request event created by the server.

export interface ServerRequestEvent<T = unknown>

Property

Modifiers

Type

Description

env

EnvGetter

getClientConn

() => ClientConn

getWritableStream

ServerResponseHandler<T>

locale

string | undefined

mode

ServerRequestMode

platform

QwikCityPlatform

request

Request

url

URL

Edit this section

ServerRequestMode

export type ServerRequestMode = "dev" | "static" | "server";

Edit this section

ServerResponseHandler

export type ServerResponseHandler<T = any> = (
  status: number,
  headers: Headers,
  cookies: Cookie,
  resolve: (response: T) => void,
  requestEv: RequestEventInternal,
) => WritableStream<Uint8Array>;

References: Cookie

Edit this section

set

Sets a Response cookie header using the Set-Cookie header.

set(name: string, value: string | number | Record<string, any>, options?: CookieOptions): void;

Parameter

Type

Description

name

string

value

string | number | Record<string, any>

options

CookieOptions

(Optional)

void

status

status: number;