How to include another handler (scheduled, email) in a Worker based on a framework such as Svelte?

Hello! I'm experimenting with a new Svelte app built on Cloudflare Workers instead of Pages, and my understanding is that doing do, I can use other handlers such as an Email, Queue or Scheduler Handler. My problem is that, the app is mainly a Svelte app, so@sveltejs/adapter-cloudflare automatically creates the output file to Cloudflare Workers, with the fetch handler. Is there a good way to add other handlers in this setup?
1 Reply
h4ckedneko
h4ckedneko3mo ago
Since SvelteKit generates a _worker.js on its own you cannot do it in SvelteKit. But you can move the other stuffs (email, queue, scheduler) into its own worker and create a binding to your SvelteKit app to use it. For example, to use queue you have to make it like this:
apps
queue
web
apps
queue
web
The apps/queue is a separate worker that consumes the queue. The main script looks like this:
export default {
queue: async (batch) => {
for (const message of batch.messages) {
// do something with the message...
}
},
} satisfies ExportedHandler<Env>;
export default {
queue: async (batch) => {
for (const message of batch.messages) {
// do something with the message...
}
},
} satisfies ExportedHandler<Env>;
And its wrangler.toml looks like this:
name = "queue-worker"
main = "./src/index.ts"

[[queues.consumers]]
queue = "my-queue"
name = "queue-worker"
main = "./src/index.ts"

[[queues.consumers]]
queue = "my-queue"
The apps/web contains the SvelteKit app. It has a binding to the same queue that apps/queue uses. Its wrangler.toml looks like this:
name = "app-worker"
main = "./.svelte-kit/cloudflare/_worker.js"

[assets]
binding = "ASSETS"
directory = "./.svelte-kit/cloudflare"

[[queues.producers]]
queue = "my-queue"
binding = "MY_QUEUE"
name = "app-worker"
main = "./.svelte-kit/cloudflare/_worker.js"

[assets]
binding = "ASSETS"
directory = "./.svelte-kit/cloudflare"

[[queues.producers]]
queue = "my-queue"
binding = "MY_QUEUE"
Somewhere in your SvelteKit handler (+server.ts or +page.server.ts), you send to the queue like this:
export const actions = {
queue: async ({ platform }) => {
await platform.env.MY_QUEUE.send(something);
},
};
export const actions = {
queue: async ({ platform }) => {
await platform.env.MY_QUEUE.send(something);
},
};
I'm using monorepo setup but you may choose not to, you can still make multiple workers even in non-monorepo setup. Hope it helps you.

Did you find this page helpful?