Home > Back-end >  How to generate a UUID in NextJs?
How to generate a UUID in NextJs?

Time:04-13

I'm trying this

import { randomUUID } from 'crypto'
var id = randomUUID()

in my NextJs app but I'm getting this error:

index.js?46cb:369 Uncaught TypeError: (0 , crypto__WEBPACK_IMPORTED_MODULE_5__.randomUUID) is not a function at eval (index.js?bee7:8:20) at Module../pages/index.js (index.js?ts=1649816623582:5680:1) at Module.options.factory (webpack.js?ts=1649816623582:618:31) at webpack_require (webpack.js?ts=1649816623582:37:33) at fn (webpack.js?ts=1649816623582:287:21) at eval (?595a:5:16) at eval (route-loader.js?ea34:235:51)

it seems like the crypto library is available to middleware in NextJs (though it should be available at the browser) but that seems complicated to implement. can anyone suggest how to generate a UUID in NextJs?

CodePudding user response:

Because crypto is a build-in module in Node.js, you cannot use it on the client. You can use an external library like uuid or short-uuid instead:

import { v4 } from "uuid";

v4(); // deadbeef-deadbeef-deadbeef-deadbeef or some uuid

Using external cross-platform libraries allows you to use it both on the server and in the client, which would resolve the issue.

CodePudding user response:

Crypto is built-in Node module. You cannot use that in client side. Use this uuid Package

import { v4 as uuidv4 } from 'uuid';
uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d
  • Related