Deno Doc Components

Component Showcase


MarkdownSummary

Some markdown with links and symbol links, like: Router

ModuleDoc

import * as oak from "https://deno.land/x/oak@v10.5.1/mod.ts";

A middleware framework for handling HTTP with Deno.

oak works well on both Deno CLI and Deno deploy, and is inspired by koa. It works well with both the Deno CLI and Deno Deploy.

Example server

A minimal router server which responds with content on /. With Deno CLI this will listen on port 8080 and on Deploy, this will simply serve requests received on the application.

import { Application, Router } from "https://deno.land/x/oak/mod.ts";

const router = new Router();
router.get("/", (ctx) => {
  ctx.response.body = `<!DOCTYPE html>
    <html>
      <head><title>Hello oak!</title><head>
      <body>
        <h1>Hello oak!</h1>
      </body>
    </html>
  `;
});

const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());

app.listen({ port: 8080 });

Namespaces

etag
helpers
testing

Classes

Application

A class which registers middleware (via .use()) and then processes inbound requests against that middleware (via .listen()).

Context

Provides context about the current request and response to middleware functions, and the current instance being processed is the first argument provided a Middleware function.

Cookies

An interface which allows setting and accessing cookies related to both the current request and response. Each Context has a property .cookies which is an instance of this class.

FormDataReader

An interface which provides an interface to access the fields of a multipart/form-data body.

HttpError

The base class for individual classes of HTTP errors.

HttpServerNative

The oak abstraction of the Deno native HTTP server which is used internally for handling native HTTP requests. Generally users of oak do not need to worry about this class.

MultiPartStream

A class that takes a file (either a Deno.FsFile or Uint8Array) and bytes and streams the ranges as a multi-part encoded HTTP body.

NativeRequest

An internal oak abstraction for handling a Deno native request. Most users of oak do not need to worry about this abstraction.

Request

An interface which provides information about the current request. The instance related to the current request is available on the Context's .request property.

Response

An interface to control what response will be sent when the middleware finishes processing the request.

Router

An interface for registering middleware that will run when certain HTTP methods and paths are requested, as well as provides a way to parameterize parts of the requested path.

ServerSentEvent

An event which contains information which will be sent to the remote connection and be made available in an EventSource as an event. A server creates new events and dispatches them on the target which will then be sent to a client.

Enums

Status

Enum of HTTP status codes.

Variables

httpErrors

An object which contains an individual HTTP Error for each HTTP status error code (4XX and 5XX). When errors are raised related to a particular HTTP status code, they will be of the appropriate instance located on this object. Also, context's .throw() will throw errors based on the passed status code.

REDIRECT_BACK

A symbol that indicates to response.redirect() to attempt to redirect back to the request referrer. For example:

STATUS_TEXT

Map from status code to status text.

testing.mockContextState

Allows external parties to modify the context state.

Functions

composeMiddleware

Compose multiple middleware functions into a single middleware function.

createHttpError

Create a specific class of HttpError based on the status, which defaults to 500 Internal Server Error.

etag.calculate

Calculate an ETag value for an entity. If the entity is FileInfo, then the tag will default to a weak ETag. options.weak overrides any default behavior in generating the tag.

etag.factory

Create middleware that will attempt to decode the response.body into something that can be used to generate an ETag and add the ETag header to the response.

etag.getEntity

For a given Context, try to determine the response body entity that an ETag can be calculated from.

etag.ifMatch

A helper function that takes the value from the If-Match header and an entity and returns true if the ETag for the entity matches the supplied value, otherwise false.

etag.ifNoneMatch

A helper function that takes the value from the If-No-Match header and an entity and returns false if the ETag for the entity matches the supplied value, otherwise false.

helpers.getQuery

Given a context, return the .request.url.searchParams as a Map of keys and values of the params.

ifRange

Determine, by the value of an If-Range header, if a Range header should be applied to a request, returning true if it should or otherwise false.

isErrorStatus

Determines if a HTTP Status is an ErrorStatus (4XX or 5XX).

isHttpError
isRedirectStatus

Determines if a HTTP Status is a RedirectStatus (3XX).

parseRange
proxy

Middleware that provides a back-to-back proxy for requests.

send

Asynchronously fulfill a response with a file from the local file system.

testing.createMockApp

Creates a mock of Application.

testing.createMockContext

Create a mock of Context or RouterContext.

testing.createMockNext

Creates a mock next() function which can be used when calling middleware.

Interfaces

ApplicationOptions

Available options that are used when creating a new instance of Application.

BodyContentTypes
BodyOptions

Options which can be used when accessing the .body() of a request.

BodyOptionsContentTypes

When setting the contentTypes property of BodyOptions, provide additional content types which can influence how the body is decoded. This is specifically designed to allow a server to support custom or specialized media types that are not part of the public database.

ByteRange
ContextSendOptions
CookiesGetOptions
CookiesSetDeleteOptions
etag.ETagOptions
etag.FileInfo

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

FormDataBody

When reading a body in full via .read() from a FormDataReader this is what is what the value is resolved, providing a split between any fields, and multi-part files that were provided.

FormDataFile

A representation of a file that has been read from a form data body. Based on the FormDataReadOptions that were passed when reading will determine if files are written to disk or not and how they are written to disk. When written to disk, the extension of the file will be determined by the content type, with the .filename property containing the full path to the file.

FormDataReadOptions

Options which impact how the form data is decoded for a FormDataReader. All these options have sensible defaults for most applications, but can be modified for different use cases. Many of these options can have an impact on the stability of a server, especially if there is someone attempting a denial of service attack on your server, so be careful when changing the defaults.

ListenOptionsBase
ListenOptionsTls
Middleware

Middleware are functions which are chained together to deal with requests.

ProxyOptions
Route
RouterAllowedMethodsOptions
RouterContext

The context passed router middleware.

RouterMiddleware
RouterOptions
RouterParamMiddleware

Middleware that will be called by the router when handling a specific parameter, which the middleware will be called when a request matches the route parameter.

SendOptions
ServerConstructor
ServerSentEventInit
ServerSentEventTarget
testing.MockContextOptions

Options that can be set in a mock context.

Type Aliases

BodyBytes

The tagged type for "bytes" bodies.

BodyForm

The tagged type for "form" bodies.

BodyFormData

The tagged type for "form-data" bodies.

BodyJson

The tagged type for "json" bodies.

BodyReader

The tagged type for "reader" bodies.

BodyStream

The tagged type for "stream" bodies.

BodyText

The tagged type for "text" bodies.

BodyType

The type of the body, where:

BodyUndefined

The tagged type for "undefined" bodies.

ErrorStatus

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

helpers.GetParamsOptions
HTTPMethods
ListenOptions
RedirectStatus

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

RouteParams
State

ModuleIndex

Index
archive/
async/

A collection of APIs to provide help with asynchronous tasks.

bytes/

Provides helper functions to manipulate Uint8Array byte slices that are not included on the Uint8Array prototype.

collections/

This module is browser compatible.

crypto/
datetime/

This module is browser compatible.

dotenv/

Dotenv config

encoding/
examples/
flags/

This module is browser compatible.

fmt/
fs/
hash/

This module is browser compatible.

http/

Http

io/

IO

log/

log

media_types/

Provides utility functions for media types.

mime/

Mime

node/
path/

Ported mostly from https://github.com/browserify/path-browserify/ This module is browser compatible.

permissions/

Permission

signal/

Signal

streams/

Streams

testing/
textproto/

Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

uuid/

UUID

wasi/
version.ts
archive/async/bytes/collections/crypto/datetime/dotenv/encoding/examples/flags/fmt/fs/hash/http/io/log/media_types/mime/node/path/permissions/signal/streams/testing/textproto/uuid/wasi/version.ts

SymbolDoc

Application

import { Application } from "https://deno.land/x/oak@v10.5.1/mod.ts";

A class which registers middleware (via .use()) and then processes inbound requests against that middleware (via .listen()).

The context.state can be typed via passing a generic argument when constructing an instance of Application. It can also be inferred by setting the ApplicationOptions.state option when constructing the application.

Basic example

import { Application } from "https://deno.land/x/oak/mod.ts";

const app = new Application();

app.use((ctx, next) => {
  // called on each request with the context (`ctx`) of the request,
  // response, and other data.
  // `next()` is use to modify the flow control of the middleware stack.
});

app.listen({ port: 8080 });
class Application<AS extends State = Record<string, any>> extends EventTarget {
handle;
get keys(): KeyStack | Key[] | undefined;
set keys(keys: KeyStack | Key[] | undefined);
proxy: boolean;
state: AS;
 
addEventListener<S extends AS>(
type: "error",
options?: boolean | AddEventListenerOptions,
): void;
addEventListener(
type: "listen",
options?: boolean | AddEventListenerOptions,
): void;
addEventListener(
type: "error" | "listen",
options?: boolean | AddEventListenerOptions,
): void;
async listen(addr: string): Promise<void>;
async listen(options?: ListenOptions): Promise<void>;
async listen(options?: string | ListenOptions): Promise<void>;
use<S extends State = AS>(middleware: Middleware<S, Context<S, AS>>, ...middlewares: Middleware<S, Context<S, AS>>[]): Application<S extends AS ? S : (S & AS)>;
use<S extends State = AS>(...middleware: Middleware<S, Context<S, AS>>[]): Application<S extends AS ? S : (S & AS)>;
[Symbol.for("Deno.customInspect")](inspect: (value: unknown) => string);
[Symbol.for("nodejs.util.inspect.custom")](
depth: number,
options: any,
inspect: (value: unknown, options?: unknown) => string,
);
}

Tag

abstract 👎 deprecated

Usage

import * as example from "https://deno.land/x/example@v1.0.0/mod.ts";
import { MyClass } from "https://deno.land/x/example@v1.0.0/mod.ts";
import { namespace } from "https://deno.land/x/example@v1.0.0/mod.ts";

const { MyClass } = namespace;
import { type Interface } from "https://deno.land/x/example@v1.0.0/mod.ts";