Skip to content

Commit

Permalink
Expose Cloudflare execution context to server components
Browse files Browse the repository at this point in the history
Using the getEnv API for now until dai-shi#827 is resolved

Example usage:

```ts
  const ctx = getEnv("ctx") as unknown as ExecutionContext | undefined;
  ctx?.waitUntil(
    new Promise<void>((resolve) => {
      console.log("Waiting for 5 seconds")
      setTimeout(() => {
        console.log("OK, done waiting")
        resolve()
      }, 5000)
    }),
  )
```

Server console output:

```
Waiting for 5 seconds
[wrangler:inf] GET /about 200 OK (30ms)
[wrangler:inf] GET /assets/jsx-runtime-BjG_zV1W.js 304 Not Modified (6ms)
[wrangler:inf] GET /assets/index-CbskofAj.js 304 Not Modified (7ms)
[wrangler:inf] GET /assets/_layout-Shb4QlRw.css 304 Not Modified (9ms)
[wrangler:inf] GET /assets/rsc2-c69df7b3e.js 200 OK (11ms)
[wrangler:inf] GET /assets/client-kczTGGZ_.js 304 Not Modified (16ms)
[wrangler:inf] GET /assets/indexHtml-DCalQi_d.js 304 Not Modified (18ms)
[wrangler:inf] GET /assets/client-CMyJdxTj.js 304 Not Modified (21ms)
[wrangler:inf] GET /assets/rsc0-ba005381c.js 304 Not Modified (4ms)
[wrangler:inf] GET /images/favicon.png 304 Not Modified (3ms)
OK, done waiting
```

The page was already sent to the client and loaded while the promise was still executing.
  • Loading branch information
rmarscher committed Sep 11, 2024
1 parent caf582d commit 5aa44b0
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion packages/waku/src/lib/builder/serve-cloudflare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,12 @@ export default {
ctx: Parameters<typeof app.fetch>[2],
) {
if (!serveWaku) {
serveWaku = runner({ cmd: 'start', loadEntries, env });
serveWaku = runner({
cmd: 'start',
loadEntries,
// @ts-expect-error Pass the execution context to server components via env
env: { ...(ctx ? { ctx } : {}), ...env },
});
}
return app.fetch(request, env, ctx);
},
Expand Down

0 comments on commit 5aa44b0

Please sign in to comment.