Export default vs addEventListener

A year ago Cloudflare’s worker start example code was:

addEventListener("fetch", (event) => {
	event.respondWith(
		handleRequest(event.request).catch(
			(err) => new Response(err.stack, { status: 500 })
		)
	);
});

async function handleRequest(request) {
   return new Response("Hello world");
}

Now it’s

export default {
  async fetch(request, env) {
    return new Response("Hello world")
  }
}

Is there any reason why the second method is preferred over the first?

There are several reasons you might want to migrate your Workers to the module syntax:

  1. Durable Objects require the module syntax.

  2. Module Workers do not rely on any global bindings, which means the Workers runtime does not need to set up fresh execution contexts, making Module Workers safer and faster to run.

  3. Module Workers are ES Modules, which allows them to be shared and published to npm, for example. Module Workers can be imported by and composed within other Module Workers.

Thanks.

What’s the benefit of having access to the env object?

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.