ReferenceError: crypto is not defined

I have a javascript file which makes use of crypto. This file is used by both my Cloudflare Pages Functions and my Node preinstall script when running npm i. Locally, on my PC, both run fine but on Cloudflare Pages the preinstall script crashes with ReferenceError: crypto is not defined. If I add
import * as crypto from 'crypto';
import * as crypto from 'crypto';
at the top of the file, the preinstall step will run fine but the Pages Function will fail to build with
The package "crypto" wasn't found on the file system but is built into node. Add the "nodejs_compat" compatibility flag to your Pages project to enable Node.js compatibility.
The package "crypto" wasn't found on the file system but is built into node. Add the "nodejs_compat" compatibility flag to your Pages project to enable Node.js compatibility.
I do have the nodejs_compat flag enabled. Is there any way to not have to use
import * as crypto from 'crypto';
import * as crypto from 'crypto';
since this isn't required when running the preinstall script on my PC?
5 Replies
kian
kian12mo ago
nodejs_compat has modules under a node prefix, like node:crypto
Samantas5855
Samantas5855OP12mo ago
That works but aren't there any downsides to using node:crypto instead of the provided one on a pages function?
kian
kian12mo ago
Node Crypto and the Web Crypto global on Workers/Pages are different things - different functions, etc
Samantas5855
Samantas5855OP12mo ago
oh yeah right but node:crypto has webcrypto sth like
import { webcrypto } from 'node:crypto';
import { webcrypto } from 'node:crypto';
I was able to fix it by adding this at the top + replacing every occurrence of crypto with webcrypto on my script
kishanhitk
kishanhitk10mo ago
How do I do this if crypto is one of the peer dependecies and not a direct dependencies? Is there a better way to solve this?
Want results from more Discord servers?
Add your server