Skip to content

Instantly share code, notes, and snippets.

@PeterHindes
Created August 24, 2023 23:30
Show Gist options
  • Save PeterHindes/927a98de589c4d30b0dcaad5b8d70a70 to your computer and use it in GitHub Desktop.
Save PeterHindes/927a98de589c4d30b0dcaad5b8d70a70 to your computer and use it in GitHub Desktop.
Cloudflare Router

Cloudflare simple router

Just put the method and path in a string mapped to a function in the routes constant and you can have any function run when that path is fetched.

The provided file has some example functions imported from another file.

function test_endpoint (request, env, ctx) {
return new Response("test", { status: 200 });
}
function example_endpoint (request, env, ctx) {
const json = await request.json();
return new Response(json, { status: 200 ,headers: { "content-type": "application/json" },});
}
import { example_endpoint, test_endpoint } from 'example.js'
const routes = {
"GET /": () => new Response("This is the router example", { status: 200 }),
"GET /test_endpoint": test_endpoint,
"POST /example_endpoint": example_endpoint,
}
export default {
async fetch(request, env, ctx) {
console.log("Request", request);
const { pathname } = new URL(request.url);
var route = routes[`${request.method} ${pathname}`];
console.log("Route", `${request.method} ${pathname}`);
if (route) {
return route(request, env, ctx);
}
return new Response("Not found", { status: 404 });
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment