Skip to content

Commit 77028b9

Browse files
authored
doc(cloudflare): custom worker (#129)
1 parent 9c2af8e commit 77028b9

File tree

2 files changed

+45
-1
lines changed

2 files changed

+45
-1
lines changed

pages/cloudflare/howtos/_meta.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,6 @@
33
"stripeAPI": "Stripe API",
44
"dev-deploy": "Develop and Deploy",
55
"env-vars": "Enviroment Variables",
6-
"image": "Image Optimization"
6+
"image": "Image Optimization",
7+
"custom-worker": "Custom Worker"
78
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
## Custom Worker
2+
3+
The worker generated by the Cloudflare adapter only exports [a fetch handler](https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch/).
4+
5+
Sometimes your application needs to expose another type of handler (i.e. [a scheduled handler](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/)) or export a [Durable Object](https://developers.cloudflare.com/durable-objects/api/base/). This can be achieved by creating a custom worker.
6+
7+
The custom worker re-uses the generated fetch handler.
8+
9+
### Create your custom worker Worker
10+
11+
The following custom worker re-uses the generated fetch handler and adds a scheduled handler:
12+
13+
```ts
14+
// custom-worker.ts
15+
16+
// @ts-ignore `.open-next/worker.ts` is generated at build time
17+
import { default as handler } from "./.open-next/worker.js";
18+
19+
export default {
20+
fetch: handler.fetch,
21+
22+
async scheduled(event) {
23+
// ...
24+
},
25+
} satisfies ExportedHandler<CloudflareEnv>;
26+
27+
// The re-export is only required if your app uses the DO Queue and DO Tag Cache
28+
// See https://opennext.js.org/cloudflare/caching for details
29+
// @ts-ignore `.open-next/worker.ts` is generated at build time
30+
export { DOQueueHandler, DOShardedTagCache } from "./.open-next/worker.js";
31+
```
32+
33+
See [an example in the adapter repository](https://github.com/opennextjs/opennextjs-cloudflare/blob/main/examples/playground14/worker.ts).
34+
35+
### Update the entry point in your wrangler configuration
36+
37+
```diff
38+
// wrangler.jsonc
39+
{
40+
- "main": "./.open-next/worker.js"
41+
+ "main": "./path/to/custom-worker.ts",
42+
}
43+
```

0 commit comments

Comments
 (0)