Generate Stripe-style Snowflake IDs. For why you might want to do this, refer to this article: Designing APIs for humans: Object IDs.
Caution
Currently in preview stage, please use with caution
bun add @shiny/id
import { generateShinyId } from '@shiny/id'
const id = generateShinyId({
prefix: 'usr',
})
// Output example: usr_8lUf4MDxgEy
Underlying implementation: Uses nodejs-snowflake to generate a bigint snowflake, converts it to base62 format, and adds a user-defined prefix. Note: Theoretically generates up to 1,024,000 IDs per second, naturally blocking.
Important
This character format ID cannot be sorted correctly in the database. You can also store the original snowflake bigint value as the ID in the database and display the base62 format ID on the user side, e.g. getRawNumberFromShinyId('usr_8lUf4MDxgEy')
Using a Custom Epoch instead of the default 1970 will make your generated IDs shorter.
For example, in my current test, with epoch set to default 0, the generated ID is usr_8lUf4MDxgEy
; while with epoch set to current time, the generated ID is usr_yM0lunVA
, which is 3 characters shorter.
import { generateShinyId } from '@shiny/id'
const customEpoch = 1754074255256
const id = generateShinyId({
prefix: 'usr',
epoch: customEpoch
})
The default separator is _
, because double-clicking such an ID will automatically select the text — while -
does not. You can customize the separator.
import { generateShinyId } from '@shiny/id'
const id = generateShinyId({
prefix: 'usr',
separator: '-'
})
Due to the speed of single-machine Snowflake generation, multiple instance IDs are suitable for distributed ID generation. The instanceId range is 0 - 4095, and when not set, it defaults to a random number.
import { generateShinyId } from '@shiny/id'
const id = generateShinyId({
prefix: 'usr',
instanceId: 1,
})
const instanceId = getInstanceIdFromShinyId(id)
MIT