3

I'm building a URL shortener app in Node.js (v20.16.0) using Express. In my controller/user.js, I try to import uuid like this:

const { v4: uuidv4 } = require('uuid');

But when I run npm start, I get this error:

Error [ERR_REQUIRE_ESM]: require() of ES Module 
D:\NodeJs\short-url\node_modules\uuid\dist\index.js 
from D:\NodeJs\short-url\controller\user.js not supported.

3 Answers 3

7

The error happens because now UUID (onwards 12+) is ESM-only and no longer supports require().

My recommendation (since you’re on Node.js 20 and starting fresh):
Switch your project to ESM ("type": "module" in package.json) and use:

import { v4 as uuidv4 } from 'uuid';

OR

Use Node.js’s Built-in crypto Module (No Dependency Needed):


const { randomUUID } = require('crypto');
// Use randomUUID() directly
console.log(randomUUID()); // Outputs a v4 UUID

This is the simplest and most efficient solution, as it requires no additional dependencies and is built into Node.js

Sign up to request clarification or add additional context in comments.

Comments

4

robertklep's answer is great, but perhaps there's an easier approach - instead of converting your code from CJS to ESM, you can just drop the third party uuid dependency altogether, and use the built-in crypto.randomUUID. It provides UUID v4 functionality, and is available from Node.js 14.17.0, which is well in the past (and should be fine since you're using Node.js 20).

Comments

2

There's a note in the README stating that "Starting with uuid@12 CommonJS is no longer supported".

If you can convert your code to use ESM, use the following:

import { v4 as uuidv4 } from 'uuid';

If not, install an older version:

npm i uuid@11

See the aforementioned README for more information.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.