Deno Doc Components

Component Showcase

Markdown Summary

Some markdown with links and symbol links, like: Router

ModuleIndex

Index
examples/closeServer.ts
examples/cookieServer.ts
examples/echoServer.ts
examples/flashEchoServer.ts
examples/httpsServer.ts
examples/nestedRoutingServer.ts
examples/proxyServer.ts
examples/readerServer.ts
examples/routingServer.ts
examples/server.ts
examples/sseServer.ts
examples/staticServer.ts

ModuleDoc

import * as oak from "https://deno.land/x/oak@v11.1.0";

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

Using Deno's flash server

Currently, Deno's flash server is not the default, even with the --unstable flag. In order to use the flash server, you need to provide the FlashServer to the Application constructor:

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

const app = new Application({ serverConstructor: FlashServer });

// register middleware

app.listen({ port: 8080 });

Note the currently Deno's flash server requires the --unstable flag. If it isn't present, the application will error on listening.

Namespaces

A collection of APIs for dealing with ETags in requests and responses.

A collection of APIs to help assist in creating middleware.

A collection of utility APIs which can make testing of an oak application easier.

Classes

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

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.

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.

A server abstraction which manages requests from Deno's flash server.

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

The base class that all derivative HTTP extend, providing a status and an expose property.

An abstraction which wraps a Request from Deno's flash server. The constructor takes a Deferred which it will resolve when the response is ready.

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.

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.

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

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

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

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.

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

Standard HTTP status codes.

Variables

A map of HttpErrors that are unique instances for each HTTP error status code.

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

A record of all the status codes text.

Allows external parties to modify the context state.

Functions

Compose multiple middleware functions into a single middleware function.

Create an instance of an HttpError based on the status code provided.

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.

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.

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

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.

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.

A function that determines if the current environment supports Deno flash.

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

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.

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

A type guard that determines if the value is an HttpError or not.

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

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

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

Creates a mock of Application.

Create a mock of Context or RouterContext.

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

Interfaces

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

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

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.

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

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.

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.

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.

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

The context passed router middleware.

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.

Options that can be set in a mock context.

Type Aliases

The tagged type for "bytes" bodies.

The tagged type for "form" bodies.

The tagged type for "form-data" bodies.

The tagged type for "json" bodies.

The tagged type for "reader" bodies.

The tagged type for "stream" bodies.

The tagged type for "text" bodies.

The type of the body, where:

The tagged type for "undefined" bodies.

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

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

SymbolDoc

class Application
extends EventTarget
import { Application } from "https://deno.land/x/oak@v11.1.0";

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

Constructors

new
Application(options?: ApplicationOptions<AS, ServerRequest>)

Type Parameters

optional
AS extends State = Record<string, any>

the type of the application state which extends State and defaults to a simple string record.

Properties

handle

Handle an individual server request, returning the server response. This is similar to .listen(), but opening the connection and retrieving requests are not the responsibility of the application. If the generated context gets set to not to respond, then the method resolves with undefined, otherwise it resolves with a request that is compatible with std/http/server.

keys: KeyStack | Key[] | undefined

A set of keys, or an instance of KeyStack which will be used to sign cookies read and set by the application to avoid tampering with the cookies.

proxy: boolean

If true, proxy headers will be trusted when processing requests. This defaults to false.

state: AS

Generic state of the application, which can be specified by passing the generic argument when constructing:

  const app = new Application<{ foo: string }>();

Or can be contextually inferred based on setting an initial state object:

  const app = new Application({ state: { foo: "bar" } });

When a new context is created, the application's state is cloned and the state is unique to that request/response. Changes can be made to the application state that will be shared with all contexts.

Methods

addEventListener<S extends AS>(
type: "error",
options?: boolean | AddEventListenerOptions,
): void

Add an event listener for an "error" event which occurs when an un-caught error occurs when processing the middleware or during processing of the response.

addEventListener(
type: "listen",
options?: boolean | AddEventListenerOptions,
): void

Add an event listener for a "listen" event which occurs when the server has successfully opened but before any requests start being processed.

listen(addr: string): Promise<void>

Start listening for requests, processing registered middleware on each request. If the options .secure is undefined or false, the listening will be over HTTP. If the options .secure property is true, a .certFile and a .keyFile property need to be supplied and requests will be processed over HTTPS.

listen(options?: ListenOptions): Promise<void>

Start listening for requests, processing registered middleware on each request. If the options .secure is undefined or false, the listening will be over HTTP. If the options .secure property is true, a .certFile and a .keyFile property need to be supplied and requests will be processed over HTTPS.

Omitting options will default to { port: 0 } which allows the operating system to select the port.

use<S extends State = AS>(middleware: Middleware<S, Context<S, AS>>, ...middlewares: Middleware<S, Context<S, AS>>[]): Application<S extends AS ? S : (S & AS)>

Register middleware to be used with the application. Middleware will be processed in the order it is added, but middleware can control the flow of execution via the use of the next() function that the middleware function will be called with. The context object provides information about the current state of the application.

Basic usage:

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

const app = new Application();

app.use((ctx, next) => {
  ctx.request; // contains request information
  ctx.response; // setups up information to use in the response;
  await next(); // manages the flow control of the middleware execution
});

await app.listen({ port: 80 });
[Symbol.for("Deno.customInspect")](inspect: (value: unknown) => string)
[Symbol.for("nodejs.util.inspect.custom")](
depth: number,
options: any,
inspect: (value: unknown, options?: unknown) => string,
)

Tags

Re-export
Deprecated
deprecated
Abstract
abstract
Unstable
unstable
readonly
writeonly
optional

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 { myNamespace } from "https://deno.land/x/example@v1.0.0/mod.ts";
const { MyClass } = myNamespace;
import { type Interface } from "https://deno.land/x/example@v1.0.0/mod.ts";