cloudflare/vinext
Publicmirrored from https://github.com/cloudflare/vinextAvailable
examples/realworld-api-rest/worker/index.ts
37lines · modecode
| 1 | /** |
| 2 | * Cloudflare Worker entry point for vinext Pages Router. |
| 3 | * |
| 4 | * The built server entry (virtual:vinext-server-entry) exports: |
| 5 | * - renderPage(request, url, manifest) → Response |
| 6 | * - handleApiRoute(request, url) → Response |
| 7 | * |
| 8 | * Both use Web-standard Request/Response APIs, making them |
| 9 | * directly usable in a Worker fetch handler. |
| 10 | */ |
| 11 | |
| 12 | // @ts-expect-error — virtual module resolved by vinext at build time |
| 13 | import { renderPage, handleApiRoute } from "virtual:vinext-server-entry"; |
| 14 | |
| 15 | export default { |
| 16 | async fetch(request: Request): Promise<Response> { |
| 17 | try { |
| 18 | const url = new URL(request.url); |
| 19 | const pathname = url.pathname; |
| 20 | const urlWithQuery = pathname + url.search; |
| 21 | |
| 22 | // API routes |
| 23 | if (pathname.startsWith("/api/") || pathname === "/api") { |
| 24 | return await handleApiRoute(request, urlWithQuery); |
| 25 | } |
| 26 | |
| 27 | // Page routes — pass null for manifest (no SSR manifest in Workers build) |
| 28 | return await renderPage(request, urlWithQuery, null); |
| 29 | } catch (error) { |
| 30 | console.error("[vinext] Worker error:", error); |
| 31 | return new Response( |
| 32 | `Internal Server Error: ${error instanceof Error ? error.message : String(error)}`, |
| 33 | { status: 500 }, |
| 34 | ); |
| 35 | } |
| 36 | }, |
| 37 | }; |