Test in production without watermarks.
Works wherever you need it to.
Get 30 days of fully functional product.
Have it up and running in minutes.
Full access to our support engineering team during your product trial
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.
Multiple UUID Versions: It supports various versions of UUIDs, including:
To install the uuid package, use either of the following commands:
npm install uuid
npm install uuid
or
yarn add uuid
yarn add uuid
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'
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'
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'
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 ]
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:
Convert HTML content into PDF documents effortlessly. This feature is particularly useful for generating dynamic PDFs from web content.
Generate PDFs directly from URLs, allowing you to capture the content of web pages and save them as PDF files programmatically.
Merge, split, and manipulate existing PDF documents with ease. IronPDF provides functionalities such as appending pages, splitting documents, and more.
Secure your PDF documents by encrypting them with passwords or applying digital signatures. IronPDF offers options to protect your sensitive documents from unauthorized access.
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.
IronPDF is compatible with various platforms, including Windows, Linux, and macOS, making it suitable for a wide range of development environments.
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.
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
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"
Next, navigate to your project directory:
cd uuid-pdf
cd uuid-pdf
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
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();
}
}
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>
);
}
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.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):
fetch
to call an API endpoint (/api/pdf-uuid
) with query parameters (v4
, v5
, c
).<a>
element).Event Handling (handleChange
function):
text
state when the user types into the input field.Render Method:
Head
), a main section (<main>
), and various paragraphs displaying UUIDs and input field for user interaction.generatePdf
function is bound to a button click for triggering PDF generation.<style jsx>
) and globally (<style jsx global>
) using Next.js's styled-jsx.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";
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.