How to generate UUIDs in Prisma
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.
For a detailed comparison of UUIDs versus other ID methods, check out our other post comparing UUID vs GUID vs CUID vs NanoID for database primary keys.
Requirements
- Node.js
- Prisma CLI
- A database that supports UUIDs (e.g., PostgreSQL, MySQL 8.0+)
Setup Your Prisma Schema
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.
Migrate Database
Apply the migration to update the database schema.
prisma migrate dev --name init
Insert Data
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}`) }
Retrieve Data
Retrieving data remains unchanged. You can query the id
field like any other field.
const user = await prisma.user.findUnique({ where: { id: 'some-uuid', }, })
Update Data
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' }, })
Tips
- For PostgreSQL, consider using the native
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";
- For MySQL 8.0+, UUIDs are supported natively, and no additional configuration is needed.
- For SQLite, you will have to generate the UUID in your application code, as SQLite doesn't natively support UUID generation.
Conclusion
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.
Invite only
Fast. Opinionated. Collaborative. Local-first. Keyboard centric. Crafted to the last pixel. We've got 50 slots for Alpha access.
How to automate Prisma migrations in a CI/CD pipeline
Max Musing
How to implement soft deletes in Prisma
Max Musing
How to use the shadow database in Prisma
Kris Lachance
How to reset and seed a Prisma database
Max Musing
UUID vs GUID vs CUID vs NanoID: A guide to database primary keys
Max Musing
How to squash migrations in Prisma
Max Musing