NODE HELP

uuid NPM (How It Works For Developers)

Published August 13, 2024
Share:

Introduction

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 IronSoftware. Both these libraries can be used to generate unique IDs for database and generated UUID can be store 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.

    1. 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.
  2. Cross-Platform Support: The package works across different environments, including Node.js, React Native, and modern web browsers.
  3. Zero Dependencies: It has a small footprint and no dependencies, making it lightweight and easy to integrate into projects.
  4. Cryptographically Strong: The UUIDs generated are cryptographically strong, ensuring high security.

Installation

To install the uuid package, use the following command line:

npm install uuid
or
yarn add uuid
npm install uuid
or
yarn add uuid
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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'
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Alternatively, 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'
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'
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Advanced Features

  1. Namespace-Based UUIDs: You can create UUIDs based on a namespace and a name using version 3 or version 5 when you import uuid at the top of the project:
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'
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#
  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 ]
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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 secret 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"
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Next, navigate to your project directory:

cd uuid-pdf
cd uuid-pdf
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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 in 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";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";
  export default async function handler(req, res) {
    try {
      const v4t = req.query.v4;
      const v5t = req.query.v5;
      const c = req.query.c;
      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>";
      const pdf = await PdfDocument.fromHtml(content);
      const data = await pdf.saveAsBuffer();
      console.error("data PDF:", data);
      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";
// Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key";
  export default async function handler(req, res) {
    try {
      const v4t = req.query.v4;
      const v5t = req.query.v5;
      const c = req.query.c;
      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>";
      const pdf = await PdfDocument.fromHtml(content);
      const data = await pdf.saveAsBuffer();
      console.error("data PDF:", data);
      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();
    }
  }
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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, useEffect } from "react";
import { v4 as uuidv4 } from 'uuid';
import { v5 as uuidv5 } from 'uuid';
import { validate as uuidValidate, parse as uuidParse } from 'uuid';
export default function Home() {
  const [text, setText] = useState("");
  const myUUID = uuidv4();
  const MY_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
  const myV5UUID = uuidv5('IronPDF', MY_NAMESPACE);
  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf-uuid?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");
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (error) {
      console.error("Error generating PDF:", error);
    }
  };
  const handleChange = (event) => {
    setText(event.target.value);
  };
  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>{" "}
        </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;
        }
        footer {
          width: 100%;
          height: 100px;
          border-top: 1px solid #eaeaea;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        footer img {
          margin-left: 0.5rem;
        }
        footer a {
          display: flex;
          justify-content: center;
          align-items: center;
          text-decoration: none;
          color: inherit;
        }
        code {
          background: #fafafa;
          border-radius: 5px;
          padding: 0.75rem;
          font-size: 1.1rem;
          font-family:
            Menlo,
            Monaco,
            Lucida Console,
            Liberation Mono,
            DejaVu Sans Mono,
            Bitstream Vera Sans Mono,
            Courier New,
            monospace;
        }
      `}</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, useEffect } from "react";
import { v4 as uuidv4 } from 'uuid';
import { v5 as uuidv5 } from 'uuid';
import { validate as uuidValidate, parse as uuidParse } from 'uuid';
export default function Home() {
  const [text, setText] = useState("");
  const myUUID = uuidv4();
  const MY_NAMESPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
  const myV5UUID = uuidv5('IronPDF', MY_NAMESPACE);
  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf-uuid?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");
      document.body.appendChild(link);
      link.click();
      link.parentNode.removeChild(link);
    } catch (error) {
      console.error("Error generating PDF:", error);
    }
  };
  const handleChange = (event) => {
    setText(event.target.value);
  };
  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>{" "}
        </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;
        }
        footer {
          width: 100%;
          height: 100px;
          border-top: 1px solid #eaeaea;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        footer img {
          margin-left: 0.5rem;
        }
        footer a {
          display: flex;
          justify-content: center;
          align-items: center;
          text-decoration: none;
          color: inherit;
        }
        code {
          background: #fafafa;
          border-radius: 5px;
          padding: 0.75rem;
          font-size: 1.1rem;
          font-family:
            Menlo,
            Monaco,
            Lucida Console,
            Liberation Mono,
            DejaVu Sans Mono,
            Bitstream Vera Sans Mono,
            Courier New,
            monospace;
        }
      `}</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>
  );
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

Code Explanation

  1. Imports and Initial Setup:

    • Head from next/head: Used to modify the

      of the HTML document to set the title and favicon.

    • import styles from "../styles/Home.module.css": Imports local CSS styles for the component.

    • React, useState, useEffect: Essential React hooks for state management and side effects.
    • uuidv4, uuidv5, uuidValidate, uuidParse: 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 (MY_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 ( 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 (

        ), 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 (
        Now that you’ve downloaded IronPDF
        Want to deploy IronPDF to a live project for FREE?
        Not ready to buy?

        Want to deploy IronPDF to a live project for FREE?

        What’s included?
        Test in production without watermarks
        30 days fully functional product
        24/5 technical support during trial
Get your free 30-day Trial Key instantly.
Thank you.
If you'd like to speak to our licensing team:

Have a question? Get in touch with our development team.
No credit card or account creation required