Skip to footer content
NODE HELP

uuid NPM (How It Works For Developers)

The UUID (universally unique identifier) package is a popular NPM (Node Package Manager) library used to generate universally unique identifiers (UUIDs) in JavaScript applications. UUIDs are useful for creating unique keys in databases, session identifiers, and more. Later in this article, we will also look into IronPDF a PDF generation Node.js package from Iron Software. Both these libraries can be used to generate unique IDs for database and generated UUID can be stored in PDF format for archiving purposes.

Key Features

  1. RFC4122 Compliance: The UUID package supports the creation of UUIDs that comply with RFC4122, ensuring they are universally unique and standardized.
  2. Multiple UUID Versions: It supports various versions of UUIDs, including:

    • v1: Timestamp-based UUIDs.
    • v3: Namespace-based UUIDs using MD5 hashing.
    • v4: Randomly generated UUIDs.
    • v5: Namespace-based UUIDs using SHA-1 hashing.
    • v6: Timestamp-based UUIDs with reordered fields for improved sorting1.
  3. Cross-Platform Support: The package works across different environments, including Node.js, React Native, and modern web browsers.
  4. Zero Dependencies: It has a small footprint and no dependencies, making it lightweight and easy to integrate into projects.
  5. Cryptographically Strong: The UUIDs generated are cryptographically strong, ensuring high security.

Installation

To install the uuid package, use either of the following commands:

npm install uuid
npm install uuid
SHELL

or

yarn add uuid
yarn add uuid
SHELL

Basic Usage

Here’s how to generate UUID strings using the uuid package:

// Import syntax for uuid library
import { v4 as uuidv4 } from 'uuid';
// Generate a random UUID v4
const myUUID = uuidv4();
console.log(myUUID); // Example valid uuid: '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
// Import syntax for uuid library
import { v4 as uuidv4 } from 'uuid';
// Generate a random UUID v4
const myUUID = uuidv4();
console.log(myUUID); // Example valid uuid: '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'
JAVASCRIPT

Alternatively, using CommonJS syntax:

// Import using CommonJS syntax
const { v4: uuidv4 } = require('uuid');
// Generate a random UUID (version 4)
const myUUID = uuidv4();
console.log(myUUID); // Example uuid string output: '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
// Import using CommonJS syntax
const { v4: uuidv4 } = require('uuid');
// Generate a random UUID (version 4)
const myUUID = uuidv4();
console.log(myUUID); // Example uuid string output: '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
JAVASCRIPT

Advanced Features

  1. Namespace-Based UUIDs: You can create UUIDs based on a namespace and a name using version 3 or version 5:
import { v5 as uuidv5 } from 'uuid';

// Define a namespace UUID
const MY_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';

// Generate UUID based on the namespace and a name
const myUUID = uuidv5('my-unique-name', MY_NAMESPACE);
console.log(myUUID); // Example output: 'e4eaaaf2-d142-11e1-b3e4-080027620cdd'
import { v5 as uuidv5 } from 'uuid';

// Define a namespace UUID
const MY_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';

// Generate UUID based on the namespace and a name
const myUUID = uuidv5('my-unique-name', MY_NAMESPACE);
console.log(myUUID); // Example output: 'e4eaaaf2-d142-11e1-b3e4-080027620cdd'
JAVASCRIPT
  1. Validation and Parsing: The UUID package also provides functions to validate and parse UUIDs:
import { validate as uuidValidate, parse as uuidParse } from 'uuid';

// Validate a UUID
const isValid = uuidValidate('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d');
console.log(isValid); // true

// Convert UUID string to an array of bytes
const bytes = uuidParse('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d');
console.log(bytes); // Uint8Array(16) [ 155, 29, 235, 77, 59, 125, 75, 173, 155, 221, 43, 13, 123, 61, 203, 109 ]
import { validate as uuidValidate, parse as uuidParse } from 'uuid';

// Validate a UUID
const isValid = uuidValidate('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d');
console.log(isValid); // true

// Convert UUID string to an array of bytes
const bytes = uuidParse('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d');
console.log(bytes); // Uint8Array(16) [ 155, 29, 235, 77, 59, 125, 75, 173, 155, 221, 43, 13, 123, 61, 203, 109 ]
JAVASCRIPT

Introduction to IronPDF

uuid NPM (How It Works For Developers): Figure 1 - IronPDF

IronPDF is a popular PDF generation library used for generating, editing, and converting PDF documents. The IronPDF NPM package is specifically designed for Node.js applications. Here are some key features and details about the IronPDF NPM package:

Key Features

HTML to PDF Conversion

Convert HTML content into PDF documents effortlessly. This feature is particularly useful for generating dynamic PDFs from web content.

URL to PDF Conversion

Generate PDFs directly from URLs, allowing you to capture the content of web pages and save them as PDF files programmatically.

PDF Manipulation

Merge, split, and manipulate existing PDF documents with ease. IronPDF provides functionalities such as appending pages, splitting documents, and more.

PDF Security

Secure your PDF documents by encrypting them with passwords or applying digital signatures. IronPDF offers options to protect your sensitive documents from unauthorized access.

High-Quality Output

Produce high-quality PDF documents with precise rendering of text, images, and formatting. IronPDF ensures that your generated PDFs maintain fidelity to the original content.

Cross-Platform Compatibility

IronPDF is compatible with various platforms, including Windows, Linux, and macOS, making it suitable for a wide range of development environments.

Simple Integration

Easily integrate IronPDF into your Node.js applications using its npm package. The API is well-documented, making it straightforward to incorporate PDF generation capabilities into your projects.

Installation

To install the IronPDF NPM package, use the following command:

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
SHELL

Generate PDF Document Using IronPDF and Use the UUID NPM package

UUIDs can be used in many places in an application. It is a very atomic part in an application. UUIDs can be used as secrets for encrypted data, and these secrets can be stored in PDF documents for archiving purposes. Below, we will see an example where we generate different versions of UUID and document them in a PDF document using IronPDF.

Install Dependencies: First, create a new Next.js project (if you haven’t already) using the following command. Refer here.

npx create-next-app@latest uuid-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
npx create-next-app@latest uuid-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
SHELL

Next, navigate to your project directory:

cd uuid-pdf
cd uuid-pdf
SHELL

Install the required packages:

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add uuid
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add uuid
SHELL

Create a PDF

Now, let’s create a simple example of generating a PDF using IronPDF.

PDF Generation API: The first step is to create a backend API to generate the PDF document. Since IronPDF only runs server-side, we need to create an API to call when a user wants to generate PDF. Create a file at path pages/api/pdf.js and add the below contents.

IronPDF requires a license key, you can get it from the license page and place it in the below code.

// pages/api/pdf.js
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
import { validate as uuidValidate } from 'uuid';

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";

export default async function handler(req, res) {
  try {
    // Extract query parameters from request
    const v4t = req.query.v4;
    const v5t = req.query.v5;
    const c = req.query.c;

    // Prepare HTML content for PDF
    let content = "<h1>Demo UUID and Generate PDF Using IronPDF</h1>";
    content += "<p>V4 UUID: " + v4t + "</p>";
    content += "<p>V5 UUID: " + v5t + "</p>";
    content += "<p>Is UUID: " + c + ", Valid: " + uuidValidate(c).toString() + "</p>";

    // Generate PDF document
    const pdf = await PdfDocument.fromHtml(content);
    const data = await pdf.saveAsBuffer();
    console.log("PDF generated successfully.");

    // Set the response headers and send the PDF as a response
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader("Content-Disposition", "attachment; filename=awesomeIron.pdf");
    res.send(data);
  } catch (error) {
    console.error("Error generating PDF:", error);
    res.status(500).end();
  }
}
// pages/api/pdf.js
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
import { validate as uuidValidate } from 'uuid';

// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";

export default async function handler(req, res) {
  try {
    // Extract query parameters from request
    const v4t = req.query.v4;
    const v5t = req.query.v5;
    const c = req.query.c;

    // Prepare HTML content for PDF
    let content = "<h1>Demo UUID and Generate PDF Using IronPDF</h1>";
    content += "<p>V4 UUID: " + v4t + "</p>";
    content += "<p>V5 UUID: " + v5t + "</p>";
    content += "<p>Is UUID: " + c + ", Valid: " + uuidValidate(c).toString() + "</p>";

    // Generate PDF document
    const pdf = await PdfDocument.fromHtml(content);
    const data = await pdf.saveAsBuffer();
    console.log("PDF generated successfully.");

    // Set the response headers and send the PDF as a response
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader("Content-Disposition", "attachment; filename=awesomeIron.pdf");
    res.send(data);
  } catch (error) {
    console.error("Error generating PDF:", error);
    res.status(500).end();
  }
}
JAVASCRIPT

Now modify the index.js code as below to use the UUID and IronPDF.

import Head from "next/head";
import styles from "../styles/Home.module.css";
import React, { useState } from "react";
import { v4 as uuidv4, v5 as uuidv5, validate as uuidValidate } from 'uuid';

export default function Home() {
  const [text, setText] = useState("");

  // Generate UUIDs for demonstration
  const myUUID = uuidv4();
  const MY_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
  const myV5UUID = uuidv5('IronPDF', MY_NAMESPACE);

  // Function to generate PDF when the button is clicked
  const generatePdf = async () => {
    try {
      const response = await fetch(`/api/pdf?v4=${myUUID}&v5=${myV5UUID}&c=${text}`);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");

      // Append, click and remove the link to download the PDF
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (error) {
      console.error("Error generating PDF:", error);
    }
  };

  // Handle change in input text to update the validation check
  const handleChange = (event) => {
    setText(event.target.value);
  };

  // Render the component
  return (
    <div className={styles.container}>
      <Head>
        <title>Generate PDF Using IronPDF</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <h1>Demo UUID NPM and Generate PDF Using IronPDF</h1>
        <p>V4 UUID: {myUUID}</p>
        <p>V5 UUID: {myV5UUID}</p>
        <p>
          <span>Enter UUID to Verify:</span>{" "}
          <input type="text" value={text} onChange={handleChange} />
        </p>
        <p>Is UUID {text} Valid: {uuidValidate(text).toString()}</p>
        <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>
          Generate PDF 
        </button>
      </main>
      <style jsx>{`
        main {
          padding: 5rem 0;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
      `}</style>
      <style jsx global>{`
        html,
        body {
          padding: 0;
          margin: 0;
          font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
            Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue,
            sans-serif;
        }
        * {
          box-sizing: border-box;
        }
      `}</style>
    </div>
  );
}
import Head from "next/head";
import styles from "../styles/Home.module.css";
import React, { useState } from "react";
import { v4 as uuidv4, v5 as uuidv5, validate as uuidValidate } from 'uuid';

export default function Home() {
  const [text, setText] = useState("");

  // Generate UUIDs for demonstration
  const myUUID = uuidv4();
  const MY_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
  const myV5UUID = uuidv5('IronPDF', MY_NAMESPACE);

  // Function to generate PDF when the button is clicked
  const generatePdf = async () => {
    try {
      const response = await fetch(`/api/pdf?v4=${myUUID}&v5=${myV5UUID}&c=${text}`);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(new Blob([blob]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "awesomeIron.pdf");

      // Append, click and remove the link to download the PDF
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (error) {
      console.error("Error generating PDF:", error);
    }
  };

  // Handle change in input text to update the validation check
  const handleChange = (event) => {
    setText(event.target.value);
  };

  // Render the component
  return (
    <div className={styles.container}>
      <Head>
        <title>Generate PDF Using IronPDF</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main>
        <h1>Demo UUID NPM and Generate PDF Using IronPDF</h1>
        <p>V4 UUID: {myUUID}</p>
        <p>V5 UUID: {myV5UUID}</p>
        <p>
          <span>Enter UUID to Verify:</span>{" "}
          <input type="text" value={text} onChange={handleChange} />
        </p>
        <p>Is UUID {text} Valid: {uuidValidate(text).toString()}</p>
        <button style={{ margin: 20, padding: 5 }} onClick={generatePdf}>
          Generate PDF 
        </button>
      </main>
      <style jsx>{`
        main {
          padding: 5rem 0;
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
        }
      `}</style>
      <style jsx global>{`
        html,
        body {
          padding: 0;
          margin: 0;
          font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto,
            Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue,
            sans-serif;
        }
        * {
          box-sizing: border-box;
        }
      `}</style>
    </div>
  );
}
JAVASCRIPT

Code Explanation

  1. Imports and Initial Setup:

    • Head from next/head: Used to modify the <head> of the HTML document to set the title and favicon.
    • styles from ../styles/Home.module.css: Imports local CSS styles for the component.
    • React, useState: React hooks for state management.
    • uuidv4, uuidv5, uuidValidate: Functions imported from the UUID package for UUID generation, validation, and parsing.
  2. Component Functionality:

    • State Management:

      • useState: Manages the state of the text input field where the user enters a UUID.
      • text: State variable holding the current value of the input field.
    • UUID Generation:

      • uuidv4(): Generates a random UUID version 4.
      • MY_NAMESPACE and uuidv5('IronPDF', MY_NAMESPACE): Generates a UUID version 5 based on a given namespace.
    • PDF Generation (generatePdf function):

      • Uses fetch to call an API endpoint (/api/pdf-uuid) with query parameters (v4, v5, c).
      • Downloads the response as a blob, creates a URL for it, and generates a download link (<a> element).
      • Appends the link to the DOM, clicks it to initiate the download, and then removes it from the DOM.
    • Event Handling (handleChange function):

      • Updates the text state when the user types into the input field.
  3. Render Method:

    • Returns JSX for the component's UI structure:
      • Includes a title (Head), a main section (<main>), and various paragraphs displaying UUIDs and input field for user interaction.
      • The generatePdf function is bound to a button click for triggering PDF generation.
    • CSS styles are defined locally (<style jsx>) and globally (<style jsx global>) using Next.js's styled-jsx.

Output

uuid NPM (How It Works For Developers): Figure 2

PDF

uuid NPM (How It Works For Developers): Figure 3

IronPDF License

IronPDF runs on the license key. IronPDF npm offers a free trial license key to allow users to check out its extensive features before purchase.

Place the License Key here:

import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
import { IronPdfGlobalConfig, PdfDocument } from "@ironsoftware/ironpdf";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Add Your key here";
JAVASCRIPT

Conclusion

The UUID NPM package is a robust and versatile tool for generating unique identifiers in JavaScript applications. Its support for multiple UUID versions, cross-platform compatibility, and cryptographic strength make it an essential library for developers needing unique identifiers.

IronPDF empowers Node.js developers to elevate PDF handling capabilities within their applications, offering unparalleled functionality, reliability, and performance. By leveraging IronPDF's advanced features for PDF generation, conversion, and manipulation, developers can streamline document workflows, enhance user experiences, and meet diverse business requirements with confidence.

Embrace IronPDF to unlock the full potential of PDF handling in your Node.js projects and deliver professional-grade document solutions effortlessly. On the other hand, the UUID NPM package can be used to generate unique IDs every time they are required for encrypting data. These secret keys can be stored in PDFs using IronPDF for archiving purposes.

Darrius Serrant
Full Stack Software Engineer (WebOps)

Darrius Serrant holds a Bachelor’s degree in Computer Science from the University of Miami and works as a Full Stack WebOps Marketing Engineer at Iron Software. Drawn to coding from a young age, he saw computing as both mysterious and accessible, making it the perfect medium for creativity and problem-solving.

At Iron Software, Darrius enjoys creating new things and simplifying complex concepts to make them more understandable. As one of our resident developers, he has also volunteered to teach students, sharing his expertise with the next generation.

For Darrius, his work is fulfilling because it is valued and has a real impact.

Talk to an Expert Five Star Trust Score Rating

Ready to Get Started?