Recipes
Copy-paste patterns for dropping prefID into the tools you already use — ORMs, databases, and human-friendly codes.
Drizzle — id as the column default
Generate the id in the schema with $defaultFn, so every insert gets a typed, prefixed key automatically.
import { id } from "prefid";
import { pgTable, text } from "drizzle-orm/pg-core";
export const users = pgTable("users", {
id: text("id").primaryKey().$defaultFn(() => id("user")),
email: text("email").notNull(),
});const { id } = require("prefid");
const { pgTable, text } = require("drizzle-orm/pg-core");
const users = pgTable("users", {
id: text("id").primaryKey().$defaultFn(() => id("user")),
email: text("email").notNull(),
});Prisma — id from your app
Prisma can't call JavaScript in the schema, so declare a plain String @id and pass the value when you create the row.
// schema.prisma
model User {
id String @id // supply the value from your app
email String @unique
}import { id } from "prefid";
await prisma.user.create({
data: { id: id("user"), email },
});const { id } = require("prefid");
await prisma.user.create({
data: { id: id("user"), email },
});Postgres — the column type
A prefID is just a string. Store it as TEXT with a PRIMARY KEY (or UNIQUE) constraint — the database stays the ultimate referee for uniqueness.
-- prefID ids are strings; store them as TEXT (or VARCHAR).
CREATE TABLE users (
id TEXT PRIMARY KEY,
email TEXT NOT NULL UNIQUE
);Mongoose / MongoDB — string _id
Use a prefID as the document _id instead of an ObjectId — you get a readable, self-describing key with the same one-per-document guarantee.
import { id } from "prefid";
import { Schema, model } from "mongoose";
const userSchema = new Schema({
_id: { type: String, default: () => id("user") },
email: { type: String, required: true },
});
export const User = model("User", userSchema);const { id } = require("prefid");
const { Schema, model } = require("mongoose");
const userSchema = new Schema({
_id: { type: String, default: () => id("user") },
email: { type: String, required: true },
});
module.exports.User = model("User", userSchema);Human-friendly codes
For coupon, invite, or referral codes that people read and type, pair template with the BASE32_CROCKFORD alphabet — it drops the look-alike characters I, L, O, U.
import { template, BASE32_CROCKFORD } from "prefid";
// Coupon / invite codes: unambiguous (no 0/O or 1/l) and easy to read aloud.
const coupon = template("SAVE-####-####", { alphabet: BASE32_CROCKFORD });
coupon(); // => "SAVE-7K2M-9XQP"const { template, BASE32_CROCKFORD } = require("prefid");
// Coupon / invite codes: unambiguous (no 0/O or 1/l) and easy to read aloud.
const coupon = template("SAVE-####-####", { alphabet: BASE32_CROCKFORD });
coupon(); // => "SAVE-7K2M-9XQP"