๐ฆ Router
A router helps you call different middleware based on the method and the URL of the request. Sunder ships with a default router that will work for most small to medium size applications.
In case a request is made to a non-existing page, a 404 error is thrown.
There is also a Router.all(path, handler)
method that will catch all request methods (GET
, POST
, PATCH
, etc).
#
CFW EnvironmentIn Cloudflare Workers you can either ship your worker as a service-worker file, or a ES module. In the service-worker buildmode any KV stores and configuration values are available in the global scope (globalThis.MY_KV_STORE
), in ES Module mode. When you create an app or a router you can specify the environment type as its first generic argument, for example:
Then in a middleware you can require a certain field to be available:
When you do this it will be statically type-checked by the Typescript compiler - preventing you from making mistakes.
#
Route parametersThe router automatically extracts parameters from the URL, it is built upon the path-to-regexp
library (the same as is used by Express).
Example
Note how we write required parameters in the pointy brackets (Context<{}, {firstName: string}>
) on the handler. This allows the route to be statically type checked. If you are using Javascript just remove this type annotation.