Base62 Encoding: How Short IDs Are Generated
By Urlzee Team · Published · 6 min read
Base62 is a way of writing numbers with 62 symbols: 0-9, A-Z and a-z. URL shorteners use it, or something close to it, because those characters need no escaping in a URL and pack a lot of values into a few characters. Seven of them cover about 3.5 trillion different IDs.
What is Base62 and why do short links use it?
It is positional notation, the same idea as decimal or hexadecimal, with a bigger set of digits. Decimal has ten symbols, so two digits give 100 values. Base62 has sixty-two, so two characters give 3,844.
The alphabet is chosen for URLs. Letters and digits belong to the "unreserved" characters that can appear anywhere in a URL without percent-encoding. Symbols such as +, /, ?, # and = either have structural meaning or get encoded into sequences like %2F, which is the opposite of short. URL encoding explained covers which characters are safe and why.
A bigger alphabet means shorter codes for the same number of links:
| Encoding | Symbols | Characters needed for 1 billion IDs |
|---|---|---|
| Decimal | 10 | 9 |
| Hexadecimal | 16 | 8 |
| Base36 (digits + one letter case) | 36 | 6 |
| Base62 | 62 | 6 |
Base36 and Base62 both need six characters for a billion, but Base62 has far more headroom at that length: 62^6 is about 56.8 billion, while 36^6 is about 2.2 billion.
How many IDs does each length give?
Raise the alphabet size to the power of the length.
| Length | Base62 combinations |
|---|---|
| 4 | 14,776,336 |
| 5 | 916,132,832 |
| 6 | 56,800,235,584 |
| 7 | 3,521,614,606,208 |
| 8 | 218,340,105,584,896 |
This is why most shorteners settle on six to eight characters. Fewer and the space fills up or becomes guessable. More and the link stops being short.
How do you convert a number to Base62?
Divide by 62 repeatedly and collect the remainders. Each remainder is the index of one character, starting from the right-hand end.
To encode 1,000,000 by hand:
- 1,000,000 ÷ 62 = 16,129 remainder 2
- 16,129 ÷ 62 = 260 remainder 9
- 260 ÷ 62 = 4 remainder 12
- 4 ÷ 62 = 0 remainder 4
Reading the remainders from last to first gives 4, 12, 9, 2. With the alphabet 0-9A-Za-z, index 12 is C, so one million is 4C92.
In JavaScript, encoding and decoding look like this:
const ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
function encode(n) {
if (n === 0) return ALPHABET[0];
let out = "";
while (n > 0) {
out = ALPHABET[n % 62] + out;
n = Math.floor(n / 62);
}
return out;
}
function decode(str) {
let n = 0;
for (const ch of str) n = n * 62 + ALPHABET.indexOf(ch);
return n;
}
console.log(encode(1000000)); // "4C92"
console.log(decode("4C92")); // 1000000
This version is exact for integers up to Number.MAX_SAFE_INTEGER. For larger values, use BigInt. Note that there is no single official Base62 alphabet; some libraries put lowercase before uppercase. Encoder and decoder must agree on the order.
Should IDs come from a counter or a random generator?
Both work, and they fail in different ways.
| Counter + Base62 | Random characters | |
|---|---|---|
| Uniqueness | Guaranteed by the sequence | Checked by the database on insert |
| Code length | Starts at 1 character and grows | Fixed from the first link |
| Predictable | Yes: the next code is the next number | No |
| Reveals volume | Yes: the latest code shows how many links exist | No |
| Extra work | A shared counter across servers | A retry on the rare collision |
Predictability is the important row. If codes are sequential, anyone can walk through them and collect every destination, including links that were only ever shared privately. Services that use counters usually hide the order by scrambling the number before encoding it.
Random generation avoids the issue but must cope with collisions. The chance that a new random code clashes with an existing one is roughly the number of existing links divided by the size of the space. With 7-character Base62 codes and one million links already stored, that is about one in 3.5 million per new link. The usual way to handle it is to put a unique index on the column, attempt the insert, and generate a fresh code if the database reports a duplicate.
What is modulo bias and how do you avoid it?
Modulo bias is a subtle skew that appears when you squeeze random bytes into an alphabet with %. A random byte has 256 possible values. 256 is not a multiple of 62: it is 4 × 62 + 8. If you compute byte % 62, the first eight characters of the alphabet can be produced by five different byte values each, and the rest by only four. Those eight characters turn up 25% more often than the others.
The fix is rejection sampling: discard any byte that falls in the uneven tail, and draw another.
const ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
function randomId(length = 7) {
const limit = 256 - (256 % ALPHABET.length); // 248 for 62 symbols
let out = "";
while (out.length < length) {
const bytes = crypto.getRandomValues(new Uint8Array(length * 2));
for (const b of bytes) {
if (b < limit && out.length < length) out += ALPHABET[b % ALPHABET.length];
}
}
return out;
}
console.log(randomId()); // e.g. "q3ZkT0b"
Bytes from 248 to 255 are thrown away, so every character has exactly four byte values that map to it. The global crypto object used here is available in browsers and in Node.js 19 or later; in Node.js 18, add import { webcrypto as crypto } from "node:crypto"; at the top.
Two rules apply to any ID that should be hard to guess. Use a cryptographically secure source such as crypto.getRandomValues, never Math.random(), whose output is not designed to be unpredictable. And remove the bias, as above.
Which alphabet does Urlzee use?
Not quite Base62. Urlzee's generated codes use 56 characters:
abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789
Six characters have been taken out: 0, O and o, and 1, l and I. In many typefaces those are hard to tell apart, which matters when a link is printed on a flyer or read from a slide and typed by hand.
Each generated code is 7 characters long, giving 56^7 = 1,727,094,849,536 combinations, or about 1.7 trillion. That is roughly half the Base62 figure for the same length, a small price for codes that survive being copied by eye.
The generator works the way the example above does. It draws bytes from crypto.getRandomValues and applies rejection sampling: 256 is 4 × 56 + 32, so bytes of 224 and above are discarded and every character stays equally likely. When a link is saved, the database's unique constraint is the final check. If a generated code already exists, Urlzee generates another and tries again, up to five times.
Custom aliases follow different rules, because a person chooses them: 3 to 50 characters from letters, digits, hyphens and underscores. You can pick one with the custom URL shortener. Either way, codes are case sensitive, so /Sale and /sale are two different links.
What else matters when choosing an ID scheme?
- Readability versus density. Dropping lookalike characters costs a little capacity and saves real-world typing errors. If codes are only ever clicked or scanned, full Base62 is fine.
- Accidental words. Random letters occasionally spell something unfortunate. Some services remove vowels from the alphabet to make that less likely.
- Reserved paths. A code must not collide with real pages on the same domain. Urlzee refuses aliases such as
pricing,blogandapifor that reason. - Enumeration. Even random codes can be guessed by brute force if the space is small or requests are unlimited. A large space and rate limiting on lookups work together.
To see where ID generation sits in the whole request flow, from validation to the 302 response, read how URL shorteners work under the hood. To generate codes without writing any of this yourself, the Urlzee API returns a ready-made slug and short_url for each link you create.
Frequently asked questions
- What is Base62 encoding?
- Base62 writes a number using 62 symbols: the digits 0-9, the uppercase letters A-Z and the lowercase letters a-z. Because every symbol is safe in a URL, it is a compact way to turn a numeric ID into a short string.
- How many URLs can a 7-character Base62 code represent?
- 62 to the power of 7, which is 3,521,614,606,208, or about 3.5 trillion. Each extra character multiplies the total by 62.
- Why not use Base64 for short links?
- Standard Base64 adds +, / and = to the alphabet, and those characters have special meanings in URLs. The URL-safe variant swaps in - and _, which work but are awkward to read aloud and easy to confuse in print.
- Are short link codes case sensitive?
- With Base62 they have to be, because uppercase and lowercase letters are different digits. On Urlzee, /abc and /ABC are separate links.