How to generate UUIDs in Prisma
Robert Cooper
Robert Cooper Senior Engineer at Basedash
· January 31, 2025
Robert Cooper
Robert Cooper Senior Engineer at Basedash
· January 31, 2025
UUIDs (Universally Unique Identifiers) are often used for uniquely identifying records in a database. Prisma makes it incredibly easy to use UUIDs for this purpose. In this guide, we’ll go over how to generate and use UUIDs in Prisma.
Firstly, you’ll want to specify that a field should be a UUID in your Prisma schema. Open schema.prisma and modify it like this:
model User {
id String @id @default(uuid())
name String
}
Here, the id field is set to be a UUID. The @default(uuid()) directive tells Prisma to generate a UUID by default.
Apply the migration to update the database schema.
prisma migrate dev --name init
When you create a new user, Prisma will automatically populate the id field with a UUID.
const { PrismaClient } = require('@prisma/client')
const prisma = new PrismaClient()
async function main() {
const newUser = await prisma.user.create({
data: {
name: 'John Doe',
},
})
console.log(`Created new user: ${newUser}`)
}
Retrieving data remains unchanged. You can query the id field like any other field.
const user = await prisma.user.findUnique({
where: {
id: 'some-uuid',
},
})
You can also update a UUID field if needed, though this is generally not recommended for fields serving as primary keys.
const updatedUser = await prisma.user.update({
where: { id: 'some-uuid' },
data: { id: 'new-uuid' },
})
uuid-ossp extension for UUID generation. You can enable it via a Prisma migration.-- Enable UUID generation in PostgreSQL
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
That’s it. You’ve learned how to set up, insert, query, and update UUIDs in Prisma. It’s a straightforward process that adds a layer of uniqueness and complexity to your data models.
Written by
Senior Engineer at Basedash
Robert Cooper is a senior engineer at Basedash who builds full-stack product systems across SQL data infrastructure, APIs, and frontend architecture. His work focuses on application performance, developer velocity, and reliable self-hosted workflows that make data operations easier for teams at scale.
Basedash lets you build charts, dashboards, and reports in seconds using all your data.