Skip to content

Instantly share code, notes, and snippets.

@jacobsamo
Created November 15, 2025 08:25
Show Gist options
  • Select an option

  • Save jacobsamo/b62a13e65bbc2c7a188a1806efa9d978 to your computer and use it in GitHub Desktop.

Select an option

Save jacobsamo/b62a13e65bbc2c7a188a1806efa9d978 to your computer and use it in GitHub Desktop.
// Simple and compatible ID generator
const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
function generateRandomString(length: number): string {
let result = "";
const len = ALPHABET.length;
const arr = new Uint8Array(length);
// In modern environments (including Cloudflare Workers and Next.js),
// crypto is always available on globalThis
crypto.getRandomValues(arr);
for (let i = 0; i < length; i++) {
result += ALPHABET.charAt(arr[i]! % len);
}
return result;
}
export const prefixes = {
generic: "id",
user: "user",
test: "test", // <-- for tests only
} as const;
export function generateId(prefix: keyof typeof prefixes): string {
return [prefixes[prefix], generateRandomString(16)].join("_");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment