Packaging async_hooks in wrangler

I’m trying to use async_hooks in my worker code.
This is a node package so the build system does not know it by default.

I’ve added node_compat = true to wrangler.toml. I already had it there because of another package that I needed, and wrangler prompted me to add it.
Also tried adding --node-compat to wrangler publish. I think it’s the same as the toml config.

When I try to build I get a message
The package "async_hooks" wasn't found on the file system but is built into node. Are you trying to bundle for node? You can use "platform: 'node'" to do that, which will remove this error.

This seems like eshint’s message, not wrangler.

I saw this PR in workerd that was merged and was supposedly made it possible to use async_hooks in. I don’t know what’s the relation between workerd and cf workers. Is cf using workerd latest, or do they have their own version?

I believe the CF is using this rollup plugin to build with node compatibility. However, it is from 3 years ago and does not mention async_hooks in its supported packages list.

Another possible relevant PR is this one, which is still open.

Does anyone have any clue on how to enable this package?

It is.

Seems unlikely that a polyfill would ever get the functionality so waiting for it to be available in the Workers runtime appears to be the only bet.

Runtime releases are usually every 2 weeks, so latest changes in workerd take some time to be in the live runtime.

Notably, it’s not the entire async_hooks package.

  • The AsyncLocalStorage implementation provided by Workers intentionally omits support for the asyncLocalStorage.enterWith() and asyncLocalStorage.disable() methods.

  • Workers does not implement the full async_hooks API upon which Node.js’ implementation of AsyncLocalStorage is built.

  • Workers does not implement the ability to create an AsyncResource with an explicitly identified trigger context as allowed by Node.js. This means that a new AsyncResource will always be bound to the async context in which it was created.

Thanks, @KianNH
So if the above workerd was merged last week, it is expected to become available within a week or so?
This is great news.
I’m only using and asyncLocalStorage.getStore(), so I believe it should work.

I’ll check up again next week


Yesterday only I tested a pages functions application with asyncLocalStorage.enterWith() and asyncLocalStorage.getStore() and it is working fine without any issue.

I am starting wrangler dev server using following command -

wrangler pages dev --compatibility-date=2023-03-07 --compatibility-flag=nodejs_compat --port 8888 --proxy 30051 -- yarn preview