unjs / unenv

🕊️ Convert javaScript code to be runtime agnostic
MIT License
358 stars 19 forks source link

cloudflare-pages uses crypto polyfill but cant find methods #110

Closed gritworks closed 1 year ago

gritworks commented 1 year ago

Describe the feature

I am creating a nuxt3 app and want to swap vercel for cloudflare-pages.

Currently its deployed on vercel, not sure why the (probably incomplete?) crypto polyfill provided by unenv is no issue here. The app is running fine. of course the preset for nitro is different.

On cloudflare-pages there seems to be an issue with libraries depending on unenv

as someone mentioned it was worth trying to override unenv for these packages above to be of version 1.2.2 (in package.json)

this wont work either as it looks like jose is depending on newer exports from unenv. ("types" is not exported from util polyfill by unenv but wanted by jose) so the util library is a core node library that seems to be polyfilled incompletely also. Correct me if i'm wrong as i'm no expert at all when it comes to node.

I further looked at the possibility to maybe inject missing functions with the vite bundler but it seems only to be possible with core library's.

Hope this makes any sense

Kind regards, Wouter

Additional information

AwesomeDude091 commented 1 year ago

I think it’s because nitro compiles it into a different format. https://nitro.unjs.io/deploy/providers/cloudflare

Also I can confirm this is an issue

AwesomeDude091 commented 1 year ago

The above Pull Request allows for sidebase/nuxt-auth to compile on Cloudflare

Hebilicious commented 1 year ago

Hi @AwesomeDude091, this error isn't necessarily related to unenv, but to the fact that sidebase/nuxt-auth isn't compatible with cloudflare.

You could use this module I made for my personal needs https://github.com/Hebilicious/authjs-nuxt

What's happening is that despite the fact that some of nuxt-auth dependencies use the "node:crypto" module, which isn't a node only API. While you could try to polyfill it with unenv, you might run into other issues. The proper fix is to use packages that uses "crypto" ("web:crypto" in node.js) if you're not using node.js environments.

pi0 commented 1 year ago

121 adds all necessary exports (unimplemented) to make sure builds won't fail if simply try to import Node.js crypto apis and not being used.

As @Hebilicious mentioned, ideally we should depend on libraries that are compatible with web crypto and crypto subtle only.

This is the purpose of unenv to ensure Node.js compatibility but unfortunately, user land implementation of crypto is so costly (>500kb) that we can't.

Also for worker environments, we shall leverage their native Node.js compatibility (see Cloudflare Node.js compatibility).