A tiny, secure, URL-friendly unique string ID generator for C.
- Small. 199 bytes. Header-only. No dependencies other than libc.
- Safe. Uses
getentropy(3)
, a modern, reliable, secure randomness source. - Short IDs. A default Nano ID is 15 characters shorter than a UUIDv4 while encoding 4 bits more entropy.
- Portable. POSIX-compliant. Available in 29 programming languages.
#include <nanoid.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
char id[NANOIDLEN + 1] = "";
if (nanoidgen(id, NANOIDLEN))
return EXIT_FAILURE;
puts(id);
}
$ cc main.c -o example
$ ./example
V1StGXR8_Z5jdHi6B-myT
Nano IDs are unique string IDs where each character is an alphanumeric, a hyphen, or an underscore. Think of them as random unpadded Base64url strings. You've already seen this format elsewhere: on YouTube!
A default Nano ID is 21 characters long, encoding 126 bits of entropy at 6 bits per character.
nanoid.h
is a self-contained Nano ID generator built on top of the
getentropy(3)
randomness source. It's as portable as getentropy(3)
itself, which is a part of the POSIX.1-2024 standard. Just grab the header and
use it wherever you wish!
Works out of the box on NetBSD, OpenBSD, Linux, Android, macOS, illumos,
Solaris, FreeBSD, DragonFly, Haiku, GNU Hurd, Fuchsia, Emscripten, and WASI.
Windows support requires a getentropy(3)
shim.
To include nanoid(3)
copy nanoid.h
and LICENSE.txt
to your
project.
To build nanoidgen(1)
run make nanoidgen
.
To build and install the project use Meson:
meson setup ../nanoid && \
ninja -C ../nanoid && \
sudo ninja -C ../nanoid install
See the PDF manual at https://lukateras.github.io/nanoid.h/man.pdf.
#include <nanoid.h>
-
macro
NANOIDLEN
The default Nano ID length of 21.
-
static inline function
int *nanoidgen(char *buffer, size_t length)
Fills the buffer with a Nano ID of the specified length up to
GETENTROPY_MAX
(256).Returns the return value of
getentropy(3)
.
$ nanoidgen [length]
Generates a Nano ID of the default length (21), or the specified length within
1 and GETENTROPY_MAX
(256), and prints it to the standard output.
Port of Nano ID by Andrey Sitnik.
Original logo by Anton Lovchikov.
Social preview background texture by Tuomo.
Social preview logo assistance by Tanya Nevskaya.