Repository navigation
Cloudflare
Utilities to help web development for Cloudflare hosting.
@jsweb/utils/cloudflare/workers
Helper module to simplify development for Cloudflare Workers, and for Cloudflare Pages Functions in "Advanced Mode", which is nothing else than a Worker (https://developers.cloudflare.com/pages/platform/functions/advanced-mode/).
A class to easily implement a router to your cloud functions endpoints.
import { SimpleRouter } from '@jsweb/utils/cloudflare/workers'
import LoremIpsum from './lorem/ipsum'
import DolorSit from './dolor/sit'
import {
AmetConsecturGet,
AmetConsecturPost,
AmetConsecturPut,
AmetConsecturDelete
} from './amet/consectur'
const api = new SimpleRouter('/api/') // Instance with a base URL pathname
// Each route can accept one or more methods
api.set('lorem/ispum', { GET: LoremIpsum })
api.set('dolor/sit', { POST: DolorSit })
api.set('amet/consectur', {
GET: AmetConsecturGet,
POST: AmetConsecturPost,
PUT: AmetConsecturPut,
DELETE: AmetConsecturDelete,
})
export default api.handler()
// Any request to other URL paths will fall back to the Cloudflare ASSETS server,
// to serve your static files, for example.It is also possible to create more instances with different base paths. The .handler() method can receive other SimpleRouter instances as arguments to build a router's stack, handling all of them.
import { SimpleRouter } from '@jsweb/utils/cloudflare/workers'
// ...
const api = new SimpleRouter('/api/')
// ...
const data = new SimpleRouter('/data/')
// ...
const ws = new SimpleRouter('/ws/')
// ...
export default api.handler(data, ws)Cloudflare Pages Functions server has some issues around HTTP status responses when you are using the standalone function structure described in their documentation.
For example, if you send a POST request to a non-existent URL path, it responds with a
405 Method Not Allowedinstead of a404 Not Found. That is a totally wrong response to a non-existent URL. This was already reported to the dev support team, but they think that is correct. (https://community.cloudflare.com/t/wrong-http-status-response-when-post-to-a-non-existent-function-url/443624)
But SimpleRouter is intelligent enough to handle proper HTTP responses for common request cases:
-
404 Not Found: If any request is sent to a non-existent URL path under the router base path, for ANY HTTP METHOD -
405 Method Not Allowed: ONLY IF a request is sent to a VALID URL path under the router base path, but the endpoint DOES NOT ACCEPT THE INCOMING HTTP METHOD
If the request is ok, so it hits your function, and you can handle proper responses according to your logic.
Ex.:
import type { WorkerEnv, WorkerFunction } from '@jsweb/utils/cloudflare/workers'
interface Env extends WorkerEnv {
DATA: KVNamespace
}
const endpoint: WorkerFunction<Env> = async function({ req, env, url }) {
// **req** is the Request object
const { form } = await req.json<any>()
// **env** is Cloudflare Worker Env object
const data = await env.DATA.get('...')
// **url** is a URL object instance for the request, just a gift from SimpleRouter 😉
const key = url.searchParams.get('key')
// Do your magic...
try {
// ...
return new Response('Ok')
} catch (error) {
// ...
return new Response(error, { status: 500 })
}
}
export default endpoint