How to Select UUID Version in TypeORM Entity

Prakash Bhandari (PB)

Prakash Bhandari (PB)Loading..

Published:

 Like 
Bookmark    

When working with TypeORM in a Node.js project, one of the most common ways to assign primary keys to your entities is by using UUIDs. They offer a unique, globally identifiable string that works well in distributed systems. But a common question arises:

"Can I choose a specific UUID version in TypeORM — like UUID v1 or v4?"

 

In this post, I’ll walk you through what TypeORM supports by default, what happens under the hood, and how you can generate your own UUIDs manually — based on my own experience building several APIs using TypeORM.

 

The Question

Let’s say you’re using the following code in your entity:

import { Entity, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn('uuid')
  uuid: string;
}

Now you might wonder — can I specify the UUID version like this?

@PrimaryGeneratedColumn('uuid:4') // ??

The answer: No, not directly.

 

What TypeORM Does by Default

TypeORM uses RFC 4122-compliant UUID v4 under the hood — but only if your database driver does not have a built-in UUID function.

So in most setups (especially with PostgreSQL), when you write:

@PrimaryGeneratedColumn('uuid')
uuid: string;

You're already getting UUID v4, even though you don’t explicitly mention the version.

 

What If You Want a Different UUID Version?

If you want to manually control which version of UUID is used — or even use custom short IDs — you can simply skip @PrimaryGeneratedColumn and use @PrimaryColumn instead, and assign the value manually.

Here’s how I do it in practice:

import { Entity, PrimaryColumn } from 'typeorm';
import { v4 as uuidv4 } from 'uuid'; // or v1, v3, v5

@Entity()
export class Product {
  @PrimaryColumn()
  uuid: string = uuidv4(); // Replace with uuidv1() if you want version 1
}

This gives you full control over the UUID generation logic and version. You can even plug in other ID generators like nanoid or cuid if you prefer shorter IDs.

 

Things to Watch Out For

Ensure the UUID library (e.g. uuid) is installed:

npm install uuid

Be careful not to assign the same ID manually for multiple entries — always regenerate or check uniqueness before saving.

 

To summarize:

  • TypeORM’s 'uuid' type already uses UUID v4 in most cases.
  • You can't specify the version directly like 'uuid:4' in the decorator.
  • If you need control, generate UUIDs yourself and use @PrimaryColumn().

 

This is exactly how I’ve handled UUIDs in multiple backend projects — especially when I needed shorter or custom IDs across microservices.

Tried something similar? Stuck somewhere?
Drop your comment below and let’s talk about it.

💬 You can also reply to others — welcome curious minds and helpful answers!

Discussion (0)

Login to Post Comment!