ai / nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript

Home Page:https://zelark.github.io/nano-id-cc/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Issue while running in Firebase Emulator (Cloud Functions)

virajp opened this issue · comments

Issue: Getting following error while running inside Firebase Functions

Error [ERR_REQUIRE_ESM]: require() of ES Module ./node_modules/nanoid/index.js from ./cff/lib/utils/idGeneration.js not supported.
Instead change the require of index.js in ./cff/lib/utils/idGeneration.js to a dynamic import() which is available in all CommonJS modules.
    at Object.<anonymous> (./cff/lib/utils/idGeneration.js:4:18) {
  code: 'ERR_REQUIRE_ESM'
}

Setup:

  • TypeScript v5.3.2
  • NodeJS v20.10.0
  • Firebase Emulator (Firebase v12.9.1)
  • nanoid v5.0.3

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2017",
    "module": "CommonJS",
    "strict": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "useUnknownInCatchVariables": true,
    "lib": [
      "ES2017",
      "DOM",
    ],
    "typeRoots": [
      "types",
      "node_modules/@types",
    ],
  },
  "compileOnSave": true,
  "include": [
    "src",
  ],
  "settings": {
    "import/resolver": {
      "typescript": {}
    },
  },
}

Code:

idGeneration.ts

import { customAlphabet } from "nanoid";

export function generateId(): string {
  const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  const result = customAlphabet(alphabet, 12)();
  return result;
}

Notes:

  • Typescript build process is successful, above is runtime error.
  • Same error is thrown when the code is run outside Firebase Emulator with Node v21.3.0, Typescript v5.3.2 & nanoid v5.0.3

Temporary Fix:

Switching to the older version of nanoid (v3.3.7) does not throw this error.

As error and docs describes you need to use ESM environment. We do not support CommonJS environment for 4.x and 5.x (there is 3.x branch still supported for legacy environments).