Reputation: 1286
Can I use web crypto api in NextJS?
I tried to use
crypto.subtle.digest('SHA-256', data)
but getting an error
ReferenceError: crypto is not defined
Upvotes: 20
Views: 33621
Reputation: 155
Be sure to check your Node version. Anything below v20 gives me this error.
Upvotes: 1
Reputation: 1
I would suggest to use dynamic import. As it adds a big js chunk and increase the bundle size, look at this github thread.
For eg:
const { randomBytes } = await import('crypto');
You also need to set experimental.fallbackNodePolyfills: false
option in your next.config.js
.
You can potentially save bundle size with this.
Upvotes: 0
Reputation: 1
hi anyone findout how can we solve this issue the issue is that crypto is for nodejs envoirment so we cannot use this in next.js but i am not sure how to slove this for everyone
import * as crypto from 'crypto';
i imported this just like mentiond above but, it didnot helped me. i am still getting error,
the below metod works for me:
const crypto = typeof window === 'undefined' ? require('crypto') : null;
if (!crypto) {
throw new Error("crypto is required");
}
this works for me,but if you find any soluion let me know
Upvotes: 0
Reputation: 2094
For me, it worked when I used import * as
import * as crypto from 'crypto';
Upvotes: 12
Reputation: 176
You can use it with
const crypto = require('crypto');
or also by using
import crypto from "crypto"
Upvotes: 1