Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pages/cloudflare/howtos/_meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
"stripeAPI": "Stripe API",
"dev-deploy": "Develop and Deploy",
"env-vars": "Enviroment Variables",
"image": "Image Optimization"
"image": "Image Optimization",
"custom-worker": "Custom Worker"
}
43 changes: 43 additions & 0 deletions pages/cloudflare/howtos/custom-worker.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
## Custom Worker

The worker generated by the Cloudflare adapter only exports [a fetch handler](https://developers.cloudflare.com/workers/runtime-apis/handlers/fetch/).

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.

The custom worker re-uses the generated fetch handler.

### Create your custom worker Worker

The following custom worker re-uses the generated fetch handler and adds a scheduled handler:

```ts
// custom-worker.ts

// @ts-ignore `.open-next/worker.ts` is generated at build time
import { default as handler } from "./.open-next/worker.js";

export default {
fetch: handler.fetch,

async scheduled(event) {
// ...
},
} satisfies ExportedHandler<CloudflareEnv>;

// The re-export is only required if your app uses the DO Queue and DO Tag Cache
// See https://opennext.js.org/cloudflare/caching for details
// @ts-ignore `.open-next/worker.ts` is generated at build time
export { DOQueueHandler, DOShardedTagCache } from "./.open-next/worker.js";
```

See [an example in the adapter repository](https://github.com/opennextjs/opennextjs-cloudflare/blob/main/examples/playground14/worker.ts).

### Update the entry point in your wrangler configuration

```diff
// wrangler.jsonc
{
- "main": "./.open-next/worker.js"
+ "main": "./path/to/custom-worker.ts",
}
```