Multiple routes on a worker?

Hey, I'm new to cloudflare stuff and I was just trying to figure out how to set up a worker with multiple routes, for example can I have one action activated when http://example.com/something is called and have a different action when http://example.com/somethingelse is called?
1 Reply
Jaime
Jaime2y ago
Hi, You could assign both routes to the worker under the triggers section of the worker's settings, and then set the worker to do something like the following:
export default {
async fetch(request, env, ctx) {
const path = new URL(request.url).pathname;

switch(path) {
case "/something":
// Do something
break;
case "/something-else":
// Do something else
break;
}
return new Response("Hello World");
}
};
export default {
async fetch(request, env, ctx) {
const path = new URL(request.url).pathname;

switch(path) {
case "/something":
// Do something
break;
case "/something-else":
// Do something else
break;
}
return new Response("Hello World");
}
};
You could use the following code to do the same across different domains, or if you prefer to work with the full URLs:
export default {
async fetch(request, env, ctx) {
const url = request.url;

switch(url) {
case "https://example.com/something":
// Do something
break;
case "https://example2.com/something-else":
// Do something else
break;
}
return new Response("Hello World");
}
};
export default {
async fetch(request, env, ctx) {
const url = request.url;

switch(url) {
case "https://example.com/something":
// Do something
break;
case "https://example2.com/something-else":
// Do something else
break;
}
return new Response("Hello World");
}
};
Want results from more Discord servers?
Add your server