Last Updated: 3/9/2026
Node.js
Nano ID works seamlessly in Node.js with both ESM and CommonJS.
Requirements
- Node.js 18+ (recommended)
- Node.js 20+ for
require()with experimental flag - Node.js 22.12+ for
require()out-of-the-box
ESM (Recommended)
Setup
Add to package.json:
{
"type": "module"
}Usage
import { nanoid } from 'nanoid'
const id = nanoid()
console.log(id) //=> "V1StGXR8_Z5jdHi6B-myT"CommonJS
Node.js 22.12+
const { nanoid } = require('nanoid')
const id = nanoid()
console.log(id) //=> "V1StGXR8_Z5jdHi6B-myT"Node.js 20
Use experimental flag:
node --experimental-require-module script.jsconst { nanoid } = require('nanoid')Node.js 18
Use dynamic import:
let nanoid
async function generateId() {
if (!nanoid) {
({ nanoid } = await import('nanoid'))
}
return nanoid()
}
module.exports = { generateId }Random Generation
Nano ID uses Node.js’s crypto module:
import { webcrypto as crypto } from 'node:crypto'
crypto.getRandomValues(buffer)
// Uses OS-level CSPRNG:
// - Linux: /dev/urandom
// - macOS: SecRandomCopyBytes
// - Windows: BCryptGenRandomPerformance
Node.js version uses pooled random generation:
// Efficient: 128 IDs per system call
const ids = Array(128).fill(null).map(() => nanoid())
// Only 1 call to crypto.getRandomValues()Benchmark: ~3.7M ops/sec on modern hardware.
Use Cases
Express Server
import express from 'express'
import { nanoid } from 'nanoid'
const app = express()
app.post('/users', async (req, res) => {
const user = {
id: nanoid(),
...req.body,
createdAt: new Date()
}
await db.users.insert(user)
res.json(user)
})Database IDs
import { nanoid } from 'nanoid'
import { MongoClient } from 'mongodb'
const client = new MongoClient(url)
const db = client.db('myapp')
await db.collection('users').insertOne({
_id: nanoid(),
email: 'user@example.com'
})File Names
import { nanoid } from 'nanoid'
import { writeFile } from 'fs/promises'
const filename = `upload-${nanoid()}.jpg`
await writeFile(filename, buffer)