Search code examples
javascriptreactjswebpacknext.jscryptojs

How to generate a UUID in NextJs?


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?


Solution

  • Because crypto is a built-in module in Node.js, you cannot use it on the client. You can use an external library like uuid or short-uuid to generate uuids 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.