A tiny, secure, URL-friendly unique string ID generator for both Clojure and ClojureScript.
nano-id uses SecureRandom (Clojure) and crypto (ClojureScript) to generate cryptographically strong random IDs with a proper distribution of characters.
nano-id generates compact IDs with just 21 characters. By using a larger alphabet than UUID, nano-id can generate a greater number of unique IDs, when compared to UUID, with fewer characters (21 versus 36).
nano-id uses URL-friendly characters [A-Za-z0-9_~]
. Perfect for unique identifiers in web applications.
Add to your project.clj: [nano-id "0.9.3"]
.
The default implementation uses 64-character alphabet and generates 21-character IDs.
user=> (require '[nano-id.core :refer [nano-id]])
nil
user=> (nano-id)
"NOBHihn110UuXbF2JiKxT"
But you can pass the size
user=> (nano-id 10)
"N2g6IlJP0l"
Also you can provide your own alphabet as follow
user=> (require '[nano-id.custom :refer [generate]])
nil
user=> (def my-nano-id (generate "abc"))
#'user/my-nano-id
user=> (my-nano-id 10)
"abcbabacba"
Or your custom random number generator, for example
(let [alphabet "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~"
time-gen (fn [n] (take n (iterate #(unsigned-bit-shift-right % 6)
(quot (System/currentTimeMillis) 1000))))
time-id (generate alphabet time-gen)]
(time-id 6))
"1RJu2O"
This encodes current time using a lexicographical alphabet.
Code copyright 2018 nano-id authors and Andrey Sitnik. Code released under the MIT License.
Based on the original nanoid for JavaScript by Andrey Sitnik.