Routing & Middleware
Utilize routing libraries and middleware patterns to organize and enhance your Worker API.
API Routing Essentials
When building APIs, we need a way to direct incoming requests to the correct functions based on their URL path and HTTP method (GET, POST, etc.). This process is called routing.
Think of it like a receptionist for your API. When a request comes in, the router checks its destination and sends it to the right department (your code handler).
Manual Worker Routing
In a Cloudflare Worker, all incoming requests are handled by the fetch event listener. You can manually inspect the request's URL and method to decide what to do.
While possible for simple cases, this approach quickly becomes complex and hard to manage as your API grows.
export default {
async fetch(request) {
const url = new URL(request.url);
if (url.pathname === '/hello' && request.method === 'GET') {
return new Response('Hello from manual route!');
}
return new Response('Not Found', { status: 404 });
}
}All lessons in this course
- Designing RESTful APIs
- Routing & Middleware
- Validation & Error Handling