Workers foundations

Handle the first request

Read a standard Request and return JSON from the module Worker fetch handler using explicit status and headers.

8 minute lesson

~~~

A module Worker exports an object whose fetch method receives each incoming HTTP request, environment bindings, and an execution context.

Build responses with web APIs. Parse the URL once, route known paths, and return a real 404 for everything else. Avoid performing network or binding work at module initialization.

export default {
  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url)
    if (url.pathname === '/api/health') {
      return Response.json({ ok: true })
    }
    return Response.json({ error: 'Not found' }, { status: 404 })
  }
}

The handler’s three inputs define the request boundary: request carries user-controlled HTTP data, env provides configured capabilities, and the execution context manages work that may outlive the response. Keep module initialization limited to deterministic setup; resource access there can run before the request and can be reused in ways you did not expect.

Return a response on every path and distinguish client errors from server errors. Parse a request body only on routes and methods that need it, enforce a size and shape, and attach a request ID to both the response and safe error logs. Test evidence should include status, content type, and body:

curl -i http://localhost:8787/api/health
curl -i http://localhost:8787/missing

Add the health route and inspect it with curl, including headers and an unknown path.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →