How can I conditionally import or use the 'crypto' module only on the server-side in Next.js?

Responsive Ad Header

Question

Grade: Education Subject: Support
How can I conditionally import or use the 'crypto' module only on the server-side in Next.js?
Asked by:
93 Viewed 93 Answers

Answer (93)

Best Answer
(334)
You can use `typeof window === 'undefined'` to check if the code is running on the server. If it's running on the server, import and use the 'crypto' module. Otherwise, avoid using it or provide a browser-compatible alternative. Example: `if (typeof window === 'undefined') { const crypto = require('crypto'); /* use crypto here */ }`