How to Use Uuid in TypeScript Nodejs App
- What is UUID?
- Setting Up Your TypeScript Node.js Environment
- Generating UUIDs in TypeScript
- Using UUIDs in Your Application Logic
- Storing UUIDs in a Database
- Conclusion
- FAQ

UUIDs, or universally unique identifiers, play a crucial role in modern application development, especially when it comes to database keys and unique identifiers in distributed systems.
In this tutorial, we will dive into how to effectively use the UUID npm package in your TypeScript Node.js applications. You’ll find complete coding examples and step-by-step demonstrations to help you understand how to generate and utilize UUIDs seamlessly. By the end of this guide, you will have a solid grasp of UUIDs in your TypeScript projects, enhancing your application’s reliability and scalability.
What is UUID?
UUID stands for Universally Unique Identifier, and it is a 128-bit number used to uniquely identify information in computer systems. The beauty of UUIDs lies in their ability to be generated independently across different systems without the risk of duplication. This is particularly beneficial in distributed applications, where multiple instances may generate identifiers simultaneously.
Setting Up Your TypeScript Node.js Environment
Before diving into using UUID, you need to set up your TypeScript Node.js environment. If you haven’t already, create a new directory for your project and initialize a new Node.js application.
mkdir uuid-demo
cd uuid-demo
npm init -y
Next, you’ll want to install TypeScript and the UUID package. You can do this by running the following commands:
npm install typescript ts-node @types/node --save-dev
npm install uuid
After installing, create a tsconfig.json
file to configure TypeScript.
npx tsc --init
Now, your environment is ready, and you can start using UUID in your TypeScript application.
Generating UUIDs in TypeScript
To generate UUIDs in your TypeScript Node.js app, you will first import the UUID package. The UUID package provides several methods for generating different versions of UUIDs. The most commonly used are UUID v4 and v1.
Here’s how you can generate a UUID v4:
import { v4 as uuidv4 } from 'uuid';
const uniqueId = uuidv4();
console.log(uniqueId);
Output:
d3b0c6b4-2f3a-4f8c-bc7e-8a3f0f4e1b3f
In this code snippet, we import the v4
method from the UUID package and assign the generated UUID to the uniqueId
variable. The uuidv4()
function creates a random UUID each time it is called. This is particularly useful for creating unique identifiers for database entries, user sessions, or any other entity that requires a unique key.
Using UUIDs in Your Application Logic
Once you’ve generated UUIDs, you can incorporate them into your application logic. For example, if you’re building a simple user registration system, you might want to assign a unique identifier to each user upon registration.
Here’s an example of how to do this:
import { v4 as uuidv4 } from 'uuid';
interface User {
id: string;
name: string;
email: string;
}
const registerUser = (name: string, email: string): User => {
const user: User = {
id: uuidv4(),
name,
email,
};
return user;
};
const newUser = registerUser('Alice', 'alice@example.com');
console.log(newUser);
Output:
{ id: 'a6f8c4b2-4c2a-4b8b-9e09-5b9c1e8a1b77', name: 'Alice', email: 'alice@example.com' }
In this example, we define a User
interface that includes an id
, name
, and email
. The registerUser
function generates a unique ID for each user and returns a user object. This method ensures that each user has a unique identifier, which can be essential for database operations and user management.
Storing UUIDs in a Database
When working with databases, it’s essential to ensure that your UUIDs are stored correctly. Most databases support UUID as a data type, making it easy to store and retrieve. Here’s a brief example of how you might store a user with a UUID in a MongoDB database using Mongoose.
First, install Mongoose:
npm install mongoose
Then, create a Mongoose model for your user:
import mongoose from 'mongoose';
import { v4 as uuidv4 } from 'uuid';
const userSchema = new mongoose.Schema({
id: { type: String, default: uuidv4, unique: true },
name: String,
email: String,
});
const User = mongoose.model('User', userSchema);
const createUser = async (name: string, email: string) => {
const user = new User({ name, email });
await user.save();
console.log('User created:', user);
};
mongoose.connect('mongodb://localhost:27017/uuid-demo')
.then(() => createUser('Bob', 'bob@example.com'))
.catch(err => console.error(err));
Output:
User created: { id: 'e9a3c2b3-5d6d-4f8a-9c9c-7b9f1e8d1a2c', name: 'Bob', email: 'bob@example.com' }
In this code, we define a Mongoose schema for our user that includes a UUID as the default value for the id
field. When creating a new user, the createUser
function saves the user to the database with a unique UUID assigned automatically. This ensures that each user entry is distinct and easily retrievable.
Conclusion
Using UUIDs in your TypeScript Node.js application can significantly enhance the uniqueness and reliability of your identifiers. Whether you’re generating UUIDs for users, sessions, or any other entity, the UUID npm package makes it easy to implement. By following the steps outlined in this tutorial, you can seamlessly integrate UUIDs into your applications, ensuring that your identifiers are unique across different systems and instances.
FAQ
-
What is a UUID?
A UUID is a universally unique identifier that is used to uniquely identify information in computer systems. -
How do I install the UUID package in my Node.js app?
You can install the UUID package by runningnpm install uuid
in your project directory. -
Can I use UUIDs as primary keys in a database?
Yes, most databases support UUIDs as a data type, making them suitable for use as primary keys. -
What is the difference between UUID v4 and UUID v1?
UUID v4 is randomly generated, while UUID v1 is based on the current timestamp and the MAC address of the machine generating it. -
How do I ensure UUIDs are unique in my application?
UUIDs are designed to be unique across space and time, so using the UUID package to generate them ensures they will not collide.
Ibrahim is a Full Stack developer working as a Software Engineer in a reputable international organization. He has work experience in technologies stack like MERN and Spring Boot. He is an enthusiastic JavaScript lover who loves to provide and share research-based solutions to problems. He loves problem-solving and loves to write solutions of those problems with implemented solutions.
LinkedIn