Here's what makes a token "secure enough" for an API key or session secret, in terms of both length and format.
How long is safe โ the entropy baseline
To resist brute-force attacks, at least 128 bits (16 bytes) of randomness (entropy) is the usual recommendation โ 32 characters in hex, or about 22 in Base64. Long-lived values like session secrets are often recommended at 256 bits (32 bytes) or more.
Hex vs Base64 vs Base64URL vs UUID
Hex uses only 0-9 and a-f, making it the safest to use anywhere, though the string is longer for the same entropy. Base64 is shorter but its +, /, and = characters can break in URLs, so values going into a URL or cookie should use Base64URL, which swaps those for URL-safe characters. A UUID is 128 bits, but depending on its version some bits are fixed, giving it slightly less entropy than a pure random token.
Why it must be a cryptographically secure random
An ordinary pseudo-random generator like Math.random() uses a predictable algorithm, making it unfit for security tokens. Always use a cryptographically secure random number generator (CSPRNG) โ crypto.getRandomValues() in the browser, or crypto.randomBytes() in Node.js.