1. Using nanoid third party library [NEW!]
A tiny, secure, URL-friendly, unique string ID generator for JavaScript
https://github.com/ai/nanoid
import { nanoid } from "nanoid";
const id = nanoid(48);
2. Base 64 Encoding with URL and Filename Safe Alphabet
Page 7 of RCF 4648 describes how to encode in base 64 with URL safety.
This is natively supported by Node.js >=v14.18.0:
const crypto = require("crypto");
/** Sync */
function randomStringAsBase64Url(size) {
return crypto.randomBytes(size).toString("base64url");
}
Usage example:
randomStringAsBase64Url(20);
// Returns "AXSGpLVjne_f7w5Xg-fWdoBwbfs" which is 27 characters length.
Note that the returned string length will not match with the size argument (size != final length).
If you are using Node.js <v14.18.0 you can use an existing library like base64url to do the job. The function will be:
const crypto = require("crypto");
const base64url = require("base64url");
/** Sync */
function randomStringAsBase64Url(size) {
return base64url(crypto.randomBytes(size));
}
3. Crypto random values from limited set of characters
Beware that with this solution the generated random string is not uniformly distributed.
You can also build a strong random string from a limited set of characters like that:
const crypto = require("crypto");
/** Sync */
function randomString(length, chars) {
if (!chars) {
throw new Error("Argument 'chars' is undefined");
}
const charsLength = chars.length;
if (charsLength > 256) {
throw new Error("Argument 'chars' should not have more than 256 characters"
+ ", otherwise unpredictability will be broken");
}
const randomBytes = crypto.randomBytes(length);
let result = new Array(length);
let cursor = 0;
for (let i = 0; i < length; i++) {
cursor += randomBytes[i];
result[i] = chars[cursor % charsLength];
}
return result.join("");
}
/** Sync */
function randomAsciiString(length) {
return randomString(length,
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
}
Usage example:
randomAsciiString(20);
// Returns "rmRptK5niTSey7NlDk5y" which is 20 characters length.
randomString(20, "ABCDEFG");
// Returns "CCBAAGDGBBEGBDBECDCE" which is 20 characters length.
'a-zA-Z0-9_-'
).