ananoid 1.1.0

Edit this page

How-To: Customize NanoId Creation

Configuring generated values

While the default settings for a NanoId (21 random characters from a URL-safe alphabet consisting of: letters, numbers, underscore, or hyphen) are excellent for most use cases, it remains possible to generate instances of varying sizes, or even generate an instance from an entirely different alphabet. Further, the Ananoid library ships with several common alphabets already defined. For example, the default behavior can be mimicked as follows:

F#
let sameAsDefault = NanoId.ofOptions KnownAlphabets.UrlSafe 21

printfn $"%s{nameof sameAsDefault}: %A{sameAsDefault}"
VB
Dim sameAsDefault = KnownAlphabets.UrlSafe.MakeNanoId(size:=21)

WriteLine($"{NameOf(sameAsDefault)}: {sameAsDefault}")
C#
var sameAsDefault = KnownAlphabets.UrlSafe.MakeNanoId(size: 21);

WriteLine($"{nameof(sameAsDefault)}: {sameAsDefault}");
OUT
> dotnet fsi ~/scratches/nanoidoptions.fsx

sameAsDefault: Yq1CtDALLQCgP-XIBlzE6

But maybe we want a 64-character URL-safe identifier instead? Easy:

F#
open KnownAlphabets

let longerId = UrlSafe |> Alphabet.makeNanoId 64

printfn $"%s{nameof longerId}: %A{longerId}"
VB
Imports KnownAlphabets

Dim longerId = UrlSafe.MakeNanoId(size:=64)

WriteLine($"{NameOf(longerId)}: {longerId}")
C#
using static KnownAlphabets;

var longerId = UrlSafe.MakeNanoId(size: 64);

WriteLine($"{nameof(longerId)}: {longerId}");
OUT
> dotnet fsi ~/scratches/nanoiddefault.fsx

longerId: xXFsRF7OGQK9dXpYZp6i88wlTU6YaVGdPWAHJTyo6SjHy-whflF7Lom0oVJerVoM

Or if we wanted a 128-character value composed entirely of numbers:

F#
let numericId = Numbers.MakeNanoId(size = 128)

printfn $"%s{nameof numericId}: %A{numericId}"
VB
Dim numericId = Numbers.MakeNanoId(size:=128)

WriteLine($"{NameOf(numericId)}: {numericId}")
C#
var numericId = Numbers.MakeNanoId(size: 128);

WriteLine($"{nameof(numericId)}: {numericId}");
OUT
> dotnet fsi ~/scratches/nanoiddefault.fsx

numericId: 63605584488709912960741866160961621054311208530158529005938917360552694066372962792631604006204502313290707959512413672018143848

Further Reading

Copyright

The library is available under the Mozilla Public License, Version 2.0. For more information see the project's License file.

val sameAsDefault: obj
val printfn: format: Printf.TextWriterFormat<'T> -> 'T
val nameof: 'T -> string