Skip to main content
Module

x/keywork/router/mod.ts

A library for building V8 Isolate web apps on Cloudflare Workers, Deno, and Node.JS
Go to Latest
import * as keywork from "https://deno.land/x/keywork@v6.0.1/router/mod.ts";

Designed with familiarity in mind, the server-side routing API is inspired by Express.js, React Router, and the native Cloudflare Workers platform.

import { KeyworkRouter } from 'keywork/router'

const app = new KeyworkRouter()

app.get('/', () => 'Hello there! 👋')

export default app
import { KeyworkRouter } from 'https://deno.land/x/keywork/modules/router/mod.ts'
import { serve } from 'https://deno.land/std@0.140.0/http/server.ts'

const app = new KeyworkRouter()
serve((request) => app.fetch(request))
import { KeyworkRouter } from 'https://esm.sh/keywork/router'

const app = new KeyworkRouter()

app.get('/', () => 'Hello there! 👋')

Creating a RESTful API

Instances of Keywork#Router.KeyworkRouter | KeyworkRouter define each route handler by invoking methods that correspond with HTTP method of the same name:

HTTP Method Usage
'GET' app.get([path pattern], [RouteRequestHandler])
'POST' app.post([path pattern], [RouteRequestHandler])
'PATCH' app.patch([path pattern], [RouteRequestHandler])
'DELETE' app.delete([path pattern], [RouteRequestHandler])
'HEAD' app.head([path pattern], [RouteRequestHandler])
'OPTIONS' app.options([path pattern], [RouteRequestHandler])
'*' app.all([path pattern], [RouteRequestHandler])

GET (app.get([path pattern], [...RouteRequestHandler]))

app.get('/', () => 'Hello there! 👋')
// Hello there! 👋
app.get('/greet/:firstName', ({ params }) => `Hello there, ${params.firstName}!`)
// Hello there, Jessie!
app.get('/datetime', () => `The current datetime is: ${new Date().toLocaleTimeString()}`)
// The current datetime is: 11:35:00 AM

POST (app.post([path pattern], [...RouteRequestHandler]))

interface NewUserPayload {
  displayName: string
  email: string
}

app.post('/users', async ({ request }) => {
  const user: NewUserPayload = await request.json()

  //...
})

Path Parameters

Routes are defined with a path-to-regexp style path patterns.

app.get('/users/', ...)
app.post('/users/', ...)

app.get('/users/:userID/', ...)
app.get('/users/:userID/friends/', ...)
app.get('/articles/:articleID', ...)
Path matching is implemented via the JavaScript native URLPattern

::warning You may need a polyfill if your app uses on a runtime that hasn't yet added URLPattern class.

Learn more from the URI Module ›

::

IsomorphicFetchEvent

When creating a Keywork#Router.RouteRequestHandler | RouteRequestHandler callback, you have access to an Keywork#Events.IsomorphicFetchEvent | IsomorphicFetchEvent:

// highlight-next-line
app.get('', (event) => {
  const {
    // highlight-start
    request,
    params
    env,
    data,
    originalURL
    // highlight-end
  } = event

  return 'Hello there! 👋'
})

IsomorphicFetchEvent.request

The incoming request received by the V8 runtime.

IsomorphicFetchEvent<ExpectedParams>.params

Parameters parsed from the incoming request's URL and the route's pattern.

This can be made type-safe by providing a generic type when defining the route:

// highlight-start
interface UserProps {
  userID: string
}
// highlight-end

app.get<UserProps>('/users/:userID', (event) => {
  const { userID } = event.params
})

IsomorphicFetchEvent.env

The bound environment aliases. Bound environment aliases are mostly limited to Cloudflare Workers, and are usually defined in your wrangler.toml file.

Node.js

This is similar to process.env.

IsomorphicFetchEvent.data

Optional extra data to be passed to a route handler, usually from Keywork#Middleware | middleware.

IsomorphicFetchEvent.originalURL

The original request URL, unmodified by Keywork's middleware logic.

Middleware

Similar to Express.js's concept of Middleware, route handlers have access to a next function to pass a request off to the next route handler matching the URL pattern.

next can also be called after checking for some criteria, such as if the user has authenticated:

const authenticationRouter = new KeyworkRouter()

authenticationRouter.all('*',
(event, next) => {
  if (!isAuthenticated(event.request)) {
    throw new KeyworkResourceError("You need to be logged in to view that!", Status.Forbidden)
  }

  return next()
})

app.use(authenticationRouter)
app.get('/profile/settings', () => {...})

Overrides

Providing a request argument will override the path param parsing within KeyworkRouter. This can be useful if your middleware needs to modify or omit some request information before reaching the next route handler.

Additional Perks

The KeyworkRouter class also provides some small quality-of-life improvements over the low-level APIs of the Workers platform.

Automatic Response Parsing

Keywork will automatically infer the appropriate Response for the return type of your RouteHandler, allowing you to skip the ceremony of constructing Response with the appropriate headers

However, this behavior can be avoided by explicitly providing a Response object, or a class that extends from Response such as...

  • Keywork#HTTP/Response.CachableResponse | CachableResponse
  • Keywork#HTTP/Response.HTMLResponse | HTMLResponse
  • Keywork#HTTP/Response.JSONResponse | JSONResponse
  • Keywork#HTTP/Response.ErrorResponse | ErrorResponse

Errors

Errors in your code are caught before they crash the runtime. See Keywork#Errors.KeyworkResourceError | KeyworkResourceError for further details.

Sessions

Support for cookie-based sessions is automatically handled. See Keywork#Session.SessionMiddleware | SessionMiddleware for further details.

Related Entries

  • Keywork#URIUtils | URI Module
  • Keywork#Session | Session Module
  • Keywork#Middleware | Middleware Module

Further reading

Classes

Routes incoming HTTP requests from the user's browser to your app's route endpoints.

Variables

Used in place of the reference-sensitive instanceof

Functions

A route request handler for redirecting requests.

Checks if a given object is shaped like a KeyworkFetcher

Utility function for parsing middleware options.

Interfaces

Cloudflare Usage

Events are handled by defining and exporting an object with method handlers that correspond to event names:

Public endpoints to aid in debugging your app. Available at /keywork/*

Options to configure the Worker Router.

Middleware implementation of fetch

A function or method that handles incoming requests and replies with a Response.

An environment binding within a worker that has a fetch method. This usually is related to static assets uploaded to Cloudflare KV via Wrangler's Worker Sites.