Skip to main content

@std/http@0.215.0

latest
Works with
It is unknown whether this package works with Browsers, Deno, Node.js, Cloudflare Workers, Bun
It is unknown whether this package works with Browsers
It is unknown whether this package works with Deno
It is unknown whether this package works with Node.js
It is unknown whether this package works with Cloudflare Workers
It is unknown whether this package works with Bun
JSR Score70%
Published2 years ago (0.215.0)
default

Provides user-friendly serve on top of Deno's native HTTP server and other utilities for creating HTTP servers and clients.

Classes

c

Transforms server-sent message objects into strings for the client.

c
UserAgent(ua: string | null)

A representation of user agent string, which can be used to determine environmental information represented by the string. All properties are determined lazily.

  • browser(): Browser

    The name and version of the browser extracted from the user agent string.

  • cpu(): Cpu

    The architecture of the CPU extracted from the user agent string.

  • device(): Device

    The model, type, and vendor of a device if present in a user agent string.

  • engine(): Engine

    The name and version of the browser engine in a user agent string.

  • os(): Os

    The name and version of the operating system in a user agent string.

  • toJSON(): { browser: Browser; cpu: Cpu; device: Device; engine: Engine; os: Os; ua: string; }

    Converts the current instance to a JSON representation.

  • toString(): string

    Converts the current instance to a string.

  • ua(): string

    A read only version of the user agent string related to the instance.

c
Server(serverInit: ServerInit)

Used to construct an HTTP server.

  • addrs(): Deno.Addr[]

    Get the list of network addresses the server is listening on.

  • close(): void

    Immediately close the server listeners and associated HTTP connections.

  • closed(): boolean

    Get whether the server is closed.

  • listenAndServe(): Promise<void>

    Create a listener on the server, accept incoming connections, and handle requests on these connections with the given handler.

  • listenAndServeTls(
    certFile: string,
    keyFile: string
    ): Promise<void>

    Create a listener on the server, accept incoming connections, upgrade them to TLS, and handle requests on these connections with the given handler.

  • serve(listener: Deno.Listener): Promise<void>

    Accept incoming connections on the given listener, and handle requests on these connections with the given handler.

Functions

f
accepts(
request: Request,
...types: string[]
): string | string[] | undefined
2 overloads

Returns an array of media types accepted by the request, in order of preference. If there are no media types supplied in the request, then any media type selector will be returned.

f
acceptsEncodings(
request: Request,
...encodings: string[]
): string | string[] | undefined
2 overloads

Returns an array of content encodings accepted by the request, in order of preference. If there are no encoding supplied in the request, then ["*"] is returned, implying any encoding is accepted.

f
acceptsLanguages(
request: Request,
...langs: string[]
): string | string[] | undefined
2 overloads

Returns an array of languages accepted by the request, in order of preference. If there are no languages supplied in the request, then ["*"] is returned, imply any language is accepted.

f
calculate(
entity: Entity,
options?: ETagOptions
): Promise<string | undefined>

Calculate an ETag for an entity. When the entity is a specific set of data it will be fingerprinted as a "strong" tag, otherwise if it is just file information, it will be calculated as a weak tag.

f
deleteCookie(
headers: Headers,
name: string,
attributes?: { path?: string; domain?: string; }
): void

Set the cookie header with empty value in the headers to delete it

f
getCookies(headers: Headers): Record<string, string>

Parse cookies of a header

f
getSetCookies(headers: Headers): Cookie[]

Parse set-cookies of a header

f
ifMatch(
value: string | null,
etag: string | undefined
): boolean

A helper function that takes the value from the If-Match header and a calculated etag for the target. By using strong comparison, return true if the values match, otherwise false.

f
ifNoneMatch(
value: string | null,
etag: string | undefined
): boolean

A helper function that takes the value from the If-None-Match header and a calculated etag for the target entity and returns false if the etag for the entity matches the supplied value, otherwise true.

f
isClientErrorStatus(status: number): status is ClientErrorStatus

A type guard that determines if the status code is a client error.

f
isErrorStatus(status: number): status is ErrorStatus

A type guard that determines if the status code is an error.

f
isInformationalStatus(status: number): status is InformationalStatus

A type guard that determines if the status code is informational.

f
isRedirectStatus(status: number): status is RedirectStatus

A type guard that determines if the status code is a redirection.

f
isServerErrorStatus(status: number): status is ServerErrorStatus

A type guard that determines if the status code is a server error.

f
isStatus(status: number): status is StatusCode

Returns whether the provided number is a valid HTTP status code.

f
isSuccessfulStatus(status: number): status is SuccessfulStatus

A type guard that determines if the status code is successful.

f
parseSignedCookie(signedCookie: string): string

Parses a signed cookie to get its value.

f
serveDir(
req: Request,
opts?: ServeDirOptions
): Promise<Response>

Serves the files under the given directory root (opts.fsRoot).

f
serveFile(
req: Request,
filePath: string,
unnamed 2?: ServeFileOptions
): Promise<Response>

Returns an HTTP Response with the requested file as the body.

f
setCookie(
headers: Headers,
cookie: Cookie
): void

Set the cookie header properly in the headers

f
signCookie(
value: string,
key: CryptoKey
): Promise<string>

Returns a promise with the signed cookie value from the given cryptographic key.

f
verifyCookie(
signedCookie: string,
key: CryptoKey
): Promise<boolean>

Returns a promise of a boolean indicating whether the signed cookie is valid.

f
serve(
handler: Handler,
options?: ServeInit
): Promise<void>

Serves HTTP requests with the given handler.

f
serveListener(
listener: Deno.Listener,
handler: Handler,
options?: ServeListenerOptions
): Promise<void>

Constructs a server, accepts incoming connections on the given listener, and handles requests on these connections with the given handler.

f
serveTls(
handler: Handler,
options: ServeTlsInit
): Promise<void>

Serves HTTPS requests with the given handler.

Interfaces

I

The browser as described by a user agent string.

  • major: string | undefined

    The major version of a browser.

  • name: string | undefined

    The name of a browser.

  • version: string | undefined

    The version of a browser.

I

The CPU information as described by a user agent string.

I

The device as described by a user agent string.

  • model: string | undefined

    The model of the device.

  • type:
    "console"
    | "mobile"
    | "table"
    | "smartv"
    | "wearable"
    | "embedded"
    | undefined

    The type of device.

  • vendor: string | undefined

    The vendor of the device.

I

The browser engine as described by a user agent string.

  • name: string | undefined

    The browser engine name.

  • version: string | undefined

    The browser engine version.

I

Options for calculate.

  • algorithm: AlgorithmIdentifier

    A digest algorithm to use to calculate the etag.

  • weak: boolean

    Override the default behavior of calculating the ETag, either forcing a tag to be labelled weak or not.

I

Just the part of Deno.FileInfo that is required to calculate an ETag, so partial or user generated file information can be passed.

  • mtime: Date | null

    The last modification time of the file. This corresponds to the mtime field from stat on Linux/Mac OS and ftLastWriteTime on Windows. This may not be available on all platforms.

  • size: number

    The size of the file, in bytes.

I

The OS as described by a user agent string.

  • name: string | undefined

    The OS name.

  • version: string | undefined

    The OS version.

I

Interface for serveDir options.

  • enableCors: boolean

    Enable CORS via the "Access-Control-Allow-Origin" header.

  • etagAlgorithm: AlgorithmIdentifier

    The algorithm to use for generating the ETag.

  • fsRoot: string

    Serves the files under the given directory root. Defaults to your current directory.

  • headers: string[]

    Headers to add to each response

  • quiet: boolean

    Do not print request level logs. Defaults to false.

  • Enable directory listing.

  • showDotfiles: boolean

    Serves dotfiles.

  • showIndex: boolean

    Serves index.html as the index file of the directory.

  • urlRoot: string

    Specified that part is stripped from the beginning of the requested pathname.

I

Interface for serveFile options.

  • etagAlgorithm: AlgorithmIdentifier

    The algorithm to use for generating the ETag.

  • fileInfo: Deno.FileInfo

    An optional FileInfo object returned by Deno.stat. It is used for optimization purposes.

I

Represents a message in the Server-Sent Event (SSE) protocol.

  • comment: string

    Ignored by the client.

  • data: string

    The data field for the message. Split by new lines.

  • event: string

    A string identifying the type of event described.

  • id: string | number

    The event ID to set the EventSource object's last event ID value.

  • retry: number

    The reconnection time.

I

Information about the connection a request arrived on.

  • localAddr: Deno.Addr

    The local address of the connection.

  • remoteAddr: Deno.Addr

    The remote address of the connection.

I

Additional serve options.

  • onError: (error: unknown) => Response | Promise<Response>

    The handler to invoke when route handlers throw an error.

  • onListen: (params: { hostname: string; port: number; }) => void

    The callback which is called when the server started listening

  • signal: AbortSignal

    An AbortSignal to close the server and all connections.

I

Additional serve listener options.

  • onError: (error: unknown) => Response | Promise<Response>

    The handler to invoke when route handlers throw an error.

  • onListen: (params: { hostname: string; port: number; }) => void

    The callback which is called when the server started listening

  • signal: AbortSignal

    An AbortSignal to close the server and all connections.

I

Options for running an HTTP server.

  • handler: Handler

    The handler to invoke for individual HTTP requests.

  • onError: (error: unknown) => Response | Promise<Response>

    The handler to invoke when route handlers throw an error.

I

Initialization parameters for serveTls.

  • cert: string

    Cert chain in PEM format

  • certFile: string

    The path to the file containing the TLS certificate

  • key: string

    Server private key in PEM format

  • keyFile: string

    The path to the file containing the TLS private key.

Type Aliases

T
ClientErrorStatus =
STATUS_CODE.BadRequest
| STATUS_CODE.Unauthorized
| STATUS_CODE.PaymentRequired
| STATUS_CODE.Forbidden
| STATUS_CODE.NotFound
| STATUS_CODE.MethodNotAllowed
| STATUS_CODE.NotAcceptable
| STATUS_CODE.ProxyAuthRequired
| STATUS_CODE.RequestTimeout
| STATUS_CODE.Conflict
| STATUS_CODE.Gone
| STATUS_CODE.LengthRequired
| STATUS_CODE.PreconditionFailed
| STATUS_CODE.ContentTooLarge
| STATUS_CODE.URITooLong
| STATUS_CODE.UnsupportedMediaType
| STATUS_CODE.RangeNotSatisfiable
| STATUS_CODE.ExpectationFailed
| STATUS_CODE.Teapot
| STATUS_CODE.MisdirectedRequest
| STATUS_CODE.UnprocessableEntity
| STATUS_CODE.Locked
| STATUS_CODE.FailedDependency
| STATUS_CODE.UpgradeRequired
| STATUS_CODE.PreconditionRequired
| STATUS_CODE.TooManyRequests
| STATUS_CODE.RequestHeaderFieldsTooLarge
| STATUS_CODE.UnavailableForLegalReasons

An HTTP status that is a client error (4XX).

T
Entity = string | Uint8Array | FileInfo

Represents an entity that can be used for generating an ETag.

T
ErrorStatus = ClientErrorStatus | ServerErrorStatus

An HTTP status that is an error (4XX and 5XX).

T
InformationalStatus =
STATUS_CODE.Continue
| STATUS_CODE.SwitchingProtocols
| STATUS_CODE.Processing
| STATUS_CODE.EarlyHints

An HTTP status that is a informational (1XX).

T
RedirectStatus =
STATUS_CODE.MultipleChoices
| STATUS_CODE.MovedPermanently
| STATUS_CODE.Found
| STATUS_CODE.SeeOther
| STATUS_CODE.UseProxy
| STATUS_CODE.TemporaryRedirect
| STATUS_CODE.PermanentRedirect

An HTTP status that is a redirect (3XX).

T
Request = { headers: { get(key: string): string | null; }; }

Loose copy of Request.

  • headers: { get(key: string): string | null; }
    No documentation available
T
ServerErrorStatus =
STATUS_CODE.InternalServerError
| STATUS_CODE.NotImplemented
| STATUS_CODE.BadGateway
| STATUS_CODE.ServiceUnavailable
| STATUS_CODE.GatewayTimeout
| STATUS_CODE.HTTPVersionNotSupported
| STATUS_CODE.VariantAlsoNegotiates
| STATUS_CODE.InsufficientStorage
| STATUS_CODE.LoopDetected
| STATUS_CODE.NotExtended
| STATUS_CODE.NetworkAuthenticationRequired

An HTTP status that is a server error (5XX).

T
StatusCode = STATUS_CODE[keyof STATUS_CODE]

An HTTP status code.

T
StatusText = STATUS_TEXT[keyof STATUS_TEXT]

An HTTP status text.

T
SuccessfulStatus =
STATUS_CODE.OK
| STATUS_CODE.Created
| STATUS_CODE.Accepted
| STATUS_CODE.NonAuthoritativeInfo
| STATUS_CODE.NoContent
| STATUS_CODE.ResetContent
| STATUS_CODE.PartialContent
| STATUS_CODE.MultiStatus
| STATUS_CODE.AlreadyReported
| STATUS_CODE.IMUsed

An HTTP status that is a success (2XX).

T
Handler = (
request: Request,
connInfo: ConnInfo
) => Response | Promise<Response>

A handler for HTTP requests. Consumes a request and connection information and returns a response.

Variables

v
STATUS_CODE: { Continue: number; SwitchingProtocols: number; Processing: number; EarlyHints: number; OK: number; Created: number; Accepted: number; NonAuthoritativeInfo: number; NoContent: number; ResetContent: number; PartialContent: number; MultiStatus: number; AlreadyReported: number; IMUsed: number; MultipleChoices: number; MovedPermanently: number; Found: number; SeeOther: number; NotModified: number; UseProxy: number; TemporaryRedirect: number; PermanentRedirect: number; BadRequest: number; Unauthorized: number; PaymentRequired: number; Forbidden: number; NotFound: number; MethodNotAllowed: number; NotAcceptable: number; ProxyAuthRequired: number; RequestTimeout: number; Conflict: number; Gone: number; LengthRequired: number; PreconditionFailed: number; ContentTooLarge: number; URITooLong: number; UnsupportedMediaType: number; RangeNotSatisfiable: number; ExpectationFailed: number; Teapot: number; MisdirectedRequest: number; UnprocessableEntity: number; Locked: number; FailedDependency: number; TooEarly: number; UpgradeRequired: number; PreconditionRequired: number; TooManyRequests: number; RequestHeaderFieldsTooLarge: number; UnavailableForLegalReasons: number; InternalServerError: number; NotImplemented: number; BadGateway: number; ServiceUnavailable: number; GatewayTimeout: number; HTTPVersionNotSupported: number; VariantAlsoNegotiates: number; InsufficientStorage: number; LoopDetected: number; NotExtended: number; NetworkAuthenticationRequired: number; }

Contains the STATUS_CODE object which contains standard HTTP status codes and provides several type guards for handling status codes with type safety.

v
STATUS_TEXT: { [[STATUS_CODE.Accepted]]: string; [[STATUS_CODE.AlreadyReported]]: string; [[STATUS_CODE.BadGateway]]: string; [[STATUS_CODE.BadRequest]]: string; [[STATUS_CODE.Conflict]]: string; [[STATUS_CODE.Continue]]: string; [[STATUS_CODE.Created]]: string; [[STATUS_CODE.EarlyHints]]: string; [[STATUS_CODE.ExpectationFailed]]: string; [[STATUS_CODE.FailedDependency]]: string; [[STATUS_CODE.Forbidden]]: string; [[STATUS_CODE.Found]]: string; [[STATUS_CODE.GatewayTimeout]]: string; [[STATUS_CODE.Gone]]: string; [[STATUS_CODE.HTTPVersionNotSupported]]: string; [[STATUS_CODE.IMUsed]]: string; [[STATUS_CODE.InsufficientStorage]]: string; [[STATUS_CODE.InternalServerError]]: string; [[STATUS_CODE.LengthRequired]]: string; [[STATUS_CODE.Locked]]: string; [[STATUS_CODE.LoopDetected]]: string; [[STATUS_CODE.MethodNotAllowed]]: string; [[STATUS_CODE.MisdirectedRequest]]: string; [[STATUS_CODE.MovedPermanently]]: string; [[STATUS_CODE.MultiStatus]]: string; [[STATUS_CODE.MultipleChoices]]: string; [[STATUS_CODE.NetworkAuthenticationRequired]]: string; [[STATUS_CODE.NoContent]]: string; [[STATUS_CODE.NonAuthoritativeInfo]]: string; [[STATUS_CODE.NotAcceptable]]: string; [[STATUS_CODE.NotExtended]]: string; [[STATUS_CODE.NotFound]]: string; [[STATUS_CODE.NotImplemented]]: string; [[STATUS_CODE.NotModified]]: string; [[STATUS_CODE.OK]]: string; [[STATUS_CODE.PartialContent]]: string; [[STATUS_CODE.PaymentRequired]]: string; [[STATUS_CODE.PermanentRedirect]]: string; [[STATUS_CODE.PreconditionFailed]]: string; [[STATUS_CODE.PreconditionRequired]]: string; [[STATUS_CODE.Processing]]: string; [[STATUS_CODE.ProxyAuthRequired]]: string; [[STATUS_CODE.ContentTooLarge]]: string; [[STATUS_CODE.RequestHeaderFieldsTooLarge]]: string; [[STATUS_CODE.RequestTimeout]]: string; [[STATUS_CODE.URITooLong]]: string; [[STATUS_CODE.RangeNotSatisfiable]]: string; [[STATUS_CODE.ResetContent]]: string; [[STATUS_CODE.SeeOther]]: string; [[STATUS_CODE.ServiceUnavailable]]: string; [[STATUS_CODE.SwitchingProtocols]]: string; [[STATUS_CODE.Teapot]]: string; [[STATUS_CODE.TemporaryRedirect]]: string; [[STATUS_CODE.TooEarly]]: string; [[STATUS_CODE.TooManyRequests]]: string; [[STATUS_CODE.Unauthorized]]: string; [[STATUS_CODE.UnavailableForLegalReasons]]: string; [[STATUS_CODE.UnprocessableEntity]]: string; [[STATUS_CODE.UnsupportedMediaType]]: string; [[STATUS_CODE.UpgradeRequired]]: string; [[STATUS_CODE.UseProxy]]: string; [[STATUS_CODE.VariantAlsoNegotiates]]: string; }

A record of all the status codes text.

cookie
etag

Provides functions for dealing with and matching ETags, including calculate to calculate an etag for a given entity, ifMatch for validating if an ETag matches against a If-Match header and ifNoneMatch for validating an Etag against an If-None-Match header.

Functions

f
calculate(
entity: Entity,
options?: ETagOptions
): Promise<string | undefined>

Calculate an ETag for an entity. When the entity is a specific set of data it will be fingerprinted as a "strong" tag, otherwise if it is just file information, it will be calculated as a weak tag.

f
ifMatch(
value: string | null,
etag: string | undefined
): boolean

A helper function that takes the value from the If-Match header and a calculated etag for the target. By using strong comparison, return true if the values match, otherwise false.

f
ifNoneMatch(
value: string | null,
etag: string | undefined
): boolean

A helper function that takes the value from the If-None-Match header and a calculated etag for the target entity and returns false if the etag for the entity matches the supplied value, otherwise true.

Interfaces

I

Options for calculate.

  • algorithm: AlgorithmIdentifier

    A digest algorithm to use to calculate the etag.

  • weak: boolean

    Override the default behavior of calculating the ETag, either forcing a tag to be labelled weak or not.

I

Just the part of Deno.FileInfo that is required to calculate an ETag, so partial or user generated file information can be passed.

  • mtime: Date | null

    The last modification time of the file. This corresponds to the mtime field from stat on Linux/Mac OS and ftLastWriteTime on Windows. This may not be available on all platforms.

  • size: number

    The size of the file, in bytes.

Type Aliases

T
Entity = string | Uint8Array | FileInfo

Represents an entity that can be used for generating an ETag.

file_server

Functions

f
serveDir(
req: Request,
opts?: ServeDirOptions
): Promise<Response>

Serves the files under the given directory root (opts.fsRoot).

f
serveFile(
req: Request,
filePath: string,
unnamed 2?: ServeFileOptions
): Promise<Response>

Returns an HTTP Response with the requested file as the body.

Interfaces

I

Interface for serveDir options.

  • enableCors: boolean

    Enable CORS via the "Access-Control-Allow-Origin" header.

  • etagAlgorithm: AlgorithmIdentifier

    The algorithm to use for generating the ETag.

  • fsRoot: string

    Serves the files under the given directory root. Defaults to your current directory.

  • headers: string[]

    Headers to add to each response

  • quiet: boolean

    Do not print request level logs. Defaults to false.

  • Enable directory listing.

  • showDotfiles: boolean

    Serves dotfiles.

  • showIndex: boolean

    Serves index.html as the index file of the directory.

  • urlRoot: string

    Specified that part is stripped from the beginning of the requested pathname.

I

Interface for serveFile options.

  • etagAlgorithm: AlgorithmIdentifier

    The algorithm to use for generating the ETag.

  • fileInfo: Deno.FileInfo

    An optional FileInfo object returned by Deno.stat. It is used for optimization purposes.

negotiation

Contains the functions accepts, acceptsEncodings, and acceptsLanguages to provide content negotiation capabilities.

Functions

f
accepts(
request: Request,
...types: string[]
): string | string[] | undefined
2 overloads

Returns an array of media types accepted by the request, in order of preference. If there are no media types supplied in the request, then any media type selector will be returned.

f
acceptsEncodings(
request: Request,
...encodings: string[]
): string | string[] | undefined
2 overloads

Returns an array of content encodings accepted by the request, in order of preference. If there are no encoding supplied in the request, then ["*"] is returned, implying any encoding is accepted.

f
acceptsLanguages(
request: Request,
...langs: string[]
): string | string[] | undefined
2 overloads

Returns an array of languages accepted by the request, in order of preference. If there are no languages supplied in the request, then ["*"] is returned, imply any language is accepted.

Type Aliases

T
Request = { headers: { get(key: string): string | null; }; }

Loose copy of Request.

  • headers: { get(key: string): string | null; }
    No documentation available
server

Classes

c
Server(serverInit: ServerInit)

Used to construct an HTTP server.

  • addrs(): Deno.Addr[]

    Get the list of network addresses the server is listening on.

  • close(): void

    Immediately close the server listeners and associated HTTP connections.

  • closed(): boolean

    Get whether the server is closed.

  • listenAndServe(): Promise<void>

    Create a listener on the server, accept incoming connections, and handle requests on these connections with the given handler.

  • listenAndServeTls(
    certFile: string,
    keyFile: string
    ): Promise<void>

    Create a listener on the server, accept incoming connections, upgrade them to TLS, and handle requests on these connections with the given handler.

  • serve(listener: Deno.Listener): Promise<void>

    Accept incoming connections on the given listener, and handle requests on these connections with the given handler.

Functions

f
serve(
handler: Handler,
options?: ServeInit
): Promise<void>

Serves HTTP requests with the given handler.

f
serveListener(
listener: Deno.Listener,
handler: Handler,
options?: ServeListenerOptions
): Promise<void>

Constructs a server, accepts incoming connections on the given listener, and handles requests on these connections with the given handler.

f
serveTls(
handler: Handler,
options: ServeTlsInit
): Promise<void>

Serves HTTPS requests with the given handler.

Interfaces

I

Information about the connection a request arrived on.

  • localAddr: Deno.Addr

    The local address of the connection.

  • remoteAddr: Deno.Addr

    The remote address of the connection.

I

Additional serve options.

  • onError: (error: unknown) => Response | Promise<Response>

    The handler to invoke when route handlers throw an error.

  • onListen: (params: { hostname: string; port: number; }) => void

    The callback which is called when the server started listening

  • signal: AbortSignal

    An AbortSignal to close the server and all connections.

I

Additional serve listener options.

  • onError: (error: unknown) => Response | Promise<Response>

    The handler to invoke when route handlers throw an error.

  • onListen: (params: { hostname: string; port: number; }) => void

    The callback which is called when the server started listening

  • signal: AbortSignal

    An AbortSignal to close the server and all connections.

I

Options for running an HTTP server.

  • handler: Handler

    The handler to invoke for individual HTTP requests.

  • onError: (error: unknown) => Response | Promise<Response>

    The handler to invoke when route handlers throw an error.

I

Initialization parameters for serveTls.

  • cert: string

    Cert chain in PEM format

  • certFile: string

    The path to the file containing the TLS certificate

  • key: string

    Server private key in PEM format

  • keyFile: string

    The path to the file containing the TLS private key.

Type Aliases

T
Handler = (
request: Request,
connInfo: ConnInfo
) => Response | Promise<Response>

A handler for HTTP requests. Consumes a request and connection information and returns a response.

server_sent_event_stream

Classes

c

Transforms server-sent message objects into strings for the client.

Interfaces

I

Represents a message in the Server-Sent Event (SSE) protocol.

  • comment: string

    Ignored by the client.

  • data: string

    The data field for the message. Split by new lines.

  • event: string

    A string identifying the type of event described.

  • id: string | number

    The event ID to set the EventSource object's last event ID value.

  • retry: number

    The reconnection time.

status

Contains the STATUS_CODE object which contains standard HTTP status codes and provides several type guards for handling status codes with type safety.

Examples

Example 1

import {
  STATUS_CODE,
  STATUS_TEXT,
} from "@std/http/status";

console.log(STATUS_CODE.NotFound); // Returns 404
console.log(STATUS_TEXT[STATUS_CODE.NotFound]); // Returns "Not Found"

Example 2

import { isErrorStatus } from "@std/http/status";

const res = await fetch("https://example.com/");

if (isErrorStatus(res.status)) {
  // error handling here...
}

Functions

f
isClientErrorStatus(status: number): status is ClientErrorStatus

A type guard that determines if the status code is a client error.

f
isErrorStatus(status: number): status is ErrorStatus

A type guard that determines if the status code is an error.

f
isInformationalStatus(status: number): status is InformationalStatus

A type guard that determines if the status code is informational.

f
isRedirectStatus(status: number): status is RedirectStatus

A type guard that determines if the status code is a redirection.

f
isServerErrorStatus(status: number): status is ServerErrorStatus

A type guard that determines if the status code is a server error.

f
isStatus(status: number): status is StatusCode

Returns whether the provided number is a valid HTTP status code.

f
isSuccessfulStatus(status: number): status is SuccessfulStatus

A type guard that determines if the status code is successful.

Type Aliases

T
ClientErrorStatus =
STATUS_CODE.BadRequest
| STATUS_CODE.Unauthorized
| STATUS_CODE.PaymentRequired
| STATUS_CODE.Forbidden
| STATUS_CODE.NotFound
| STATUS_CODE.MethodNotAllowed
| STATUS_CODE.NotAcceptable
| STATUS_CODE.ProxyAuthRequired
| STATUS_CODE.RequestTimeout
| STATUS_CODE.Conflict
| STATUS_CODE.Gone
| STATUS_CODE.LengthRequired
| STATUS_CODE.PreconditionFailed
| STATUS_CODE.ContentTooLarge
| STATUS_CODE.URITooLong
| STATUS_CODE.UnsupportedMediaType
| STATUS_CODE.RangeNotSatisfiable
| STATUS_CODE.ExpectationFailed
| STATUS_CODE.Teapot
| STATUS_CODE.MisdirectedRequest
| STATUS_CODE.UnprocessableEntity
| STATUS_CODE.Locked
| STATUS_CODE.FailedDependency
| STATUS_CODE.UpgradeRequired
| STATUS_CODE.PreconditionRequired
| STATUS_CODE.TooManyRequests
| STATUS_CODE.RequestHeaderFieldsTooLarge
| STATUS_CODE.UnavailableForLegalReasons

An HTTP status that is a client error (4XX).

T
ErrorStatus = ClientErrorStatus | ServerErrorStatus

An HTTP status that is an error (4XX and 5XX).

T
InformationalStatus =
STATUS_CODE.Continue
| STATUS_CODE.SwitchingProtocols
| STATUS_CODE.Processing
| STATUS_CODE.EarlyHints

An HTTP status that is a informational (1XX).

T
RedirectStatus =
STATUS_CODE.MultipleChoices
| STATUS_CODE.MovedPermanently
| STATUS_CODE.Found
| STATUS_CODE.SeeOther
| STATUS_CODE.UseProxy
| STATUS_CODE.TemporaryRedirect
| STATUS_CODE.PermanentRedirect

An HTTP status that is a redirect (3XX).

T
ServerErrorStatus =
STATUS_CODE.InternalServerError
| STATUS_CODE.NotImplemented
| STATUS_CODE.BadGateway
| STATUS_CODE.ServiceUnavailable
| STATUS_CODE.GatewayTimeout
| STATUS_CODE.HTTPVersionNotSupported
| STATUS_CODE.VariantAlsoNegotiates
| STATUS_CODE.InsufficientStorage
| STATUS_CODE.LoopDetected
| STATUS_CODE.NotExtended
| STATUS_CODE.NetworkAuthenticationRequired

An HTTP status that is a server error (5XX).

T
StatusCode = STATUS_CODE[keyof STATUS_CODE]

An HTTP status code.

T
StatusText = STATUS_TEXT[keyof STATUS_TEXT]

An HTTP status text.

T
SuccessfulStatus =
STATUS_CODE.OK
| STATUS_CODE.Created
| STATUS_CODE.Accepted
| STATUS_CODE.NonAuthoritativeInfo
| STATUS_CODE.NoContent
| STATUS_CODE.ResetContent
| STATUS_CODE.PartialContent
| STATUS_CODE.MultiStatus
| STATUS_CODE.AlreadyReported
| STATUS_CODE.IMUsed

An HTTP status that is a success (2XX).

Variables

v
STATUS_CODE: { Continue: number; SwitchingProtocols: number; Processing: number; EarlyHints: number; OK: number; Created: number; Accepted: number; NonAuthoritativeInfo: number; NoContent: number; ResetContent: number; PartialContent: number; MultiStatus: number; AlreadyReported: number; IMUsed: number; MultipleChoices: number; MovedPermanently: number; Found: number; SeeOther: number; NotModified: number; UseProxy: number; TemporaryRedirect: number; PermanentRedirect: number; BadRequest: number; Unauthorized: number; PaymentRequired: number; Forbidden: number; NotFound: number; MethodNotAllowed: number; NotAcceptable: number; ProxyAuthRequired: number; RequestTimeout: number; Conflict: number; Gone: number; LengthRequired: number; PreconditionFailed: number; ContentTooLarge: number; URITooLong: number; UnsupportedMediaType: number; RangeNotSatisfiable: number; ExpectationFailed: number; Teapot: number; MisdirectedRequest: number; UnprocessableEntity: number; Locked: number; FailedDependency: number; TooEarly: number; UpgradeRequired: number; PreconditionRequired: number; TooManyRequests: number; RequestHeaderFieldsTooLarge: number; UnavailableForLegalReasons: number; InternalServerError: number; NotImplemented: number; BadGateway: number; ServiceUnavailable: number; GatewayTimeout: number; HTTPVersionNotSupported: number; VariantAlsoNegotiates: number; InsufficientStorage: number; LoopDetected: number; NotExtended: number; NetworkAuthenticationRequired: number; }

Contains the STATUS_CODE object which contains standard HTTP status codes and provides several type guards for handling status codes with type safety.

v
STATUS_TEXT: { [[STATUS_CODE.Accepted]]: string; [[STATUS_CODE.AlreadyReported]]: string; [[STATUS_CODE.BadGateway]]: string; [[STATUS_CODE.BadRequest]]: string; [[STATUS_CODE.Conflict]]: string; [[STATUS_CODE.Continue]]: string; [[STATUS_CODE.Created]]: string; [[STATUS_CODE.EarlyHints]]: string; [[STATUS_CODE.ExpectationFailed]]: string; [[STATUS_CODE.FailedDependency]]: string; [[STATUS_CODE.Forbidden]]: string; [[STATUS_CODE.Found]]: string; [[STATUS_CODE.GatewayTimeout]]: string; [[STATUS_CODE.Gone]]: string; [[STATUS_CODE.HTTPVersionNotSupported]]: string; [[STATUS_CODE.IMUsed]]: string; [[STATUS_CODE.InsufficientStorage]]: string; [[STATUS_CODE.InternalServerError]]: string; [[STATUS_CODE.LengthRequired]]: string; [[STATUS_CODE.Locked]]: string; [[STATUS_CODE.LoopDetected]]: string; [[STATUS_CODE.MethodNotAllowed]]: string; [[STATUS_CODE.MisdirectedRequest]]: string; [[STATUS_CODE.MovedPermanently]]: string; [[STATUS_CODE.MultiStatus]]: string; [[STATUS_CODE.MultipleChoices]]: string; [[STATUS_CODE.NetworkAuthenticationRequired]]: string; [[STATUS_CODE.NoContent]]: string; [[STATUS_CODE.NonAuthoritativeInfo]]: string; [[STATUS_CODE.NotAcceptable]]: string; [[STATUS_CODE.NotExtended]]: string; [[STATUS_CODE.NotFound]]: string; [[STATUS_CODE.NotImplemented]]: string; [[STATUS_CODE.NotModified]]: string; [[STATUS_CODE.OK]]: string; [[STATUS_CODE.PartialContent]]: string; [[STATUS_CODE.PaymentRequired]]: string; [[STATUS_CODE.PermanentRedirect]]: string; [[STATUS_CODE.PreconditionFailed]]: string; [[STATUS_CODE.PreconditionRequired]]: string; [[STATUS_CODE.Processing]]: string; [[STATUS_CODE.ProxyAuthRequired]]: string; [[STATUS_CODE.ContentTooLarge]]: string; [[STATUS_CODE.RequestHeaderFieldsTooLarge]]: string; [[STATUS_CODE.RequestTimeout]]: string; [[STATUS_CODE.URITooLong]]: string; [[STATUS_CODE.RangeNotSatisfiable]]: string; [[STATUS_CODE.ResetContent]]: string; [[STATUS_CODE.SeeOther]]: string; [[STATUS_CODE.ServiceUnavailable]]: string; [[STATUS_CODE.SwitchingProtocols]]: string; [[STATUS_CODE.Teapot]]: string; [[STATUS_CODE.TemporaryRedirect]]: string; [[STATUS_CODE.TooEarly]]: string; [[STATUS_CODE.TooManyRequests]]: string; [[STATUS_CODE.Unauthorized]]: string; [[STATUS_CODE.UnavailableForLegalReasons]]: string; [[STATUS_CODE.UnprocessableEntity]]: string; [[STATUS_CODE.UnsupportedMediaType]]: string; [[STATUS_CODE.UpgradeRequired]]: string; [[STATUS_CODE.UseProxy]]: string; [[STATUS_CODE.VariantAlsoNegotiates]]: string; }

A record of all the status codes text.

unstable_signed_cookie
user_agent

Provides UserAgent and related types to be able to provide a structured understanding of a user agent string.

Classes

c
UserAgent(ua: string | null)

A representation of user agent string, which can be used to determine environmental information represented by the string. All properties are determined lazily.

  • browser(): Browser

    The name and version of the browser extracted from the user agent string.

  • cpu(): Cpu

    The architecture of the CPU extracted from the user agent string.

  • device(): Device

    The model, type, and vendor of a device if present in a user agent string.

  • engine(): Engine

    The name and version of the browser engine in a user agent string.

  • os(): Os

    The name and version of the operating system in a user agent string.

  • toJSON(): { browser: Browser; cpu: Cpu; device: Device; engine: Engine; os: Os; ua: string; }

    Converts the current instance to a JSON representation.

  • toString(): string

    Converts the current instance to a string.

  • ua(): string

    A read only version of the user agent string related to the instance.

Interfaces

I

The browser as described by a user agent string.

  • major: string | undefined

    The major version of a browser.

  • name: string | undefined

    The name of a browser.

  • version: string | undefined

    The version of a browser.

I

The CPU information as described by a user agent string.

I

The device as described by a user agent string.

  • model: string | undefined

    The model of the device.

  • type:
    "console"
    | "mobile"
    | "table"
    | "smartv"
    | "wearable"
    | "embedded"
    | undefined

    The type of device.

  • vendor: string | undefined

    The vendor of the device.

I

The browser engine as described by a user agent string.

  • name: string | undefined

    The browser engine name.

  • version: string | undefined

    The browser engine version.

I

The OS as described by a user agent string.

  • name: string | undefined

    The OS name.

  • version: string | undefined

    The OS version.

Report package

Please provide a reason for reporting this package. We will review your report and take appropriate action.

Please review the JSR usage policy before submitting a report.

Add Package

deno add jsr:@std/http

Import symbol

import * as http from "@std/http";
or

Import directly with a jsr specifier

import * as http from "jsr:@std/http";