Alex Parij
Alex Parij

Reputation: 1286

Using Web Crypto API in NextJS, but getting error 'crypto is not defined'

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

Answers (6)

incarnate
incarnate

Reputation: 155

Be sure to check your Node version. Anything below v20 gives me this error.

Upvotes: 1

Dibyendu Biswas
Dibyendu Biswas

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

apps review
apps review

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

Vikash Rathee
Vikash Rathee

Reputation: 2094

For me, it worked when I used import * as

import * as crypto from 'crypto';

Upvotes: 12

gilzonme
gilzonme

Reputation: 176

You can use it with

const crypto = require('crypto');

or also by using

import crypto from "crypto"

Upvotes: 1

S.Chen
S.Chen

Reputation: 376

before use crypto module, just import import crypto from "crypto"

here are example for crypto

Upvotes: 22

Related Questions