NODE HELP

Hashids NPM (How It Works For Developers)

Published October 24, 2024
Share:

In modern web applications, ensuring data security and privacy is crucial. One effective way to protect sensitive information like database IDs or URLs is by using Hashids, a JavaScript encryption library that transforms numeric data into unique, reversible, and encrypted hashes. This article explores how you can seamlessly integrate Hashids into your React application to obfuscate and decode identifiers.

What is Hashids?

Hashids is a small yet powerful library that converts numeric data into a hash string. The primary goal is to obscure numerical identifiers to prevent the exposure of sensitive information. This transformation is reversible, allowing the original numeric data to be retrieved when needed. Hashids is a JavaScript library to generate YouTube-like IDs from numbers, encode sensitive data or expose your database IDs to the user securely or just obfuscate IDs from numbers.

Integrating Hashids into Your React App

To integrate Hashids into your React application, follow these steps:

Step 1: Install Hashids npm

First, install Hashids via npm in your React project:

npm install hashids
or 
yarn add hashids
npm install hashids
or 
yarn add hashids
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npm install hashids @or yarn add hashids
VB   C#

Step 2: Initialize Hashids Instance

In your React component or utility file, initialize a new Hashids instance with a salt and optionally a minimum hash length:

import { useState, useEffect } from 'react';
import Hashids from 'hashids';
const MyComponent = () => {
  const [hashids, setHashids] = useState(null);
  useEffect(() => {
    const initHashids = new Hashids('your_salt_here', 8); // Replace 'your_salt_here' with your actual salt or configure custom alphabet
    setHashids(initHashids);
  }, []);
  // Other component logic here
  return (
    <div>
      {/* Your JSX content */}
    </div>
  );
};
export default MyComponent;
import { useState, useEffect } from 'react';
import Hashids from 'hashids';
const MyComponent = () => {
  const [hashids, setHashids] = useState(null);
  useEffect(() => {
    const initHashids = new Hashids('your_salt_here', 8); // Replace 'your_salt_here' with your actual salt or configure custom alphabet
    setHashids(initHashids);
  }, []);
  // Other component logic here
  return (
    <div>
      {/* Your JSX content */}
    </div>
  );
};
export default MyComponent;
import
If True Then
	useState, useEffect
End If
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'from 'react'; import Hashids from 'hashids'; const MyComponent = () => { const [hashids, setHashids] = useState(Nothing); useEffect(() => { const initHashids = New Hashids('your_salt_here', 8); setHashids(initHashids); }, []); Return(<div> {} </div>); }; export default MyComponent;
VB   C#

Replace `'your_salt_here'` with a unique string (salt) that you use to customize the hash output.

Step 3: Encode and Decode Data

Once initialized, you can use Hashids to encode and decode numeric data. For instance, encoding a database ID:

const encodedId = hashids.encode(12345); // Example: 'B0zGbvA9' non sequential ids
const encodedId = hashids.encode(12345); // Example: 'B0zGbvA9' non sequential ids
const encodedId = hashids.encode(12345) ' Example: 'B0zGbvA9' non sequential ids
VB   C#

And decoding it back to the original ID:

const decodedIds = hashids.decode('B0zGbvA9'); // Example: [12345]
const decodedIds = hashids.decode('B0zGbvA9'); // Example: [12345]
const decodedIds = hashids.decode( 'B0zGbvA9'); ' Example: [12345]
VB   C#

Step 4: Utilize Hashids in Components

Integrate Hashids within your React components where necessary. For example, passing hashed IDs as props:

const MyComponent = ({ id }) => {
  const encodedId = hashids ? hashids.encode(id) : '';
  return (
    <div>
      <p>Encoded ID: {encodedId}</p>
      {/* Other JSX content */}
    </div>
  );
};
const MyComponent = ({ id }) => {
  const encodedId = hashids ? hashids.encode(id) : '';
  return (
    <div>
      <p>Encoded ID: {encodedId}</p>
      {/* Other JSX content */}
    </div>
  );
};
'INSTANT VB TODO TASK: Lambda expressions and anonymous methods are not converted by Instant VB if local variables of the outer method are referenced within the anonymous method:
const MyComponent = ({ id }) =>
If True Then
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'  const encodedId = hashids ? hashids.encode(id) : ''; Return(<div> <p> Encoded ID: {encodedId}</p> {} </div>); };
VB   C#

Benefits of Using Hashids in React

  • Security: Hashids obscures numeric IDs, enhancing data privacy and security tool preventing direct mapping to sensitive information.

  • Ease of Integration: Simple npm installation and straightforward API make Hashids easy to implement in React applications.

  • Flexibility: Customizable hash length and salt provide flexibility to adapt hashes to your application's security needs.

Introducing IronPDF

IronPDF is a powerful Node.js PDF library from Iron Software that allows developers to generate and edit PDFs in their .NET projects. Whether you need to create PDFs from HTML, manipulate existing PDFs, or convert web pages to PDF format, IronPDF has got you covered.

Hashids NPM (How It Works For Developers): Figure 1 - IronPDF for Node.js: The Node.js PDF Library

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 Documents Using IronPDF and Use the HashIDs NPM package

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 hashids-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
npx create-next-app@latest hashids-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'npx create-@next-app@latest hashids-pdf --use-npm --example "https://github.com/vercel/next-learn/tree/main/basics/learn-starter"
VB   C#

Next, navigate to your project directory:

cd hashids-pdf
cd hashids-pdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'cd hashids-pdf
VB   C#

Install the required packages:

yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add hashids
yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64
yarn add hashids
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'yarn add @ironsoftware/ironpdf @ironsoftware/ironpdf-engine-windows-x64 yarn add hashids
VB   C#

Create a PDF

Now, let’s create a simple example of generating a PDF using IronPDF. In your Next.js component (e.g., pages/index.tsx), add the following code:

PDF Generation API: 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 a 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 initHashids = new Hashids('IronPDF Is Awesome and this is the salt', 8); 
    const f = req.query.f;
    const l = initHashids.encode(f);
    let content = "<h1>Demo Hashids and Generate PDF Using IronPDF</h1>"
    content+="<p>Input:"+f+"</p>";
    content+="<p>HashID:"+l+"</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 initHashids = new Hashids('IronPDF Is Awesome and this is the salt', 8); 
    const f = req.query.f;
    const l = initHashids.encode(f);
    let content = "<h1>Demo Hashids and Generate PDF Using IronPDF</h1>"
    content+="<p>Input:"+f+"</p>";
    content+="<p>HashID:"+l+"</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
If True Then
	IronPdfGlobalConfig, PdfDocument
End If
from "@ironsoftware/ironpdf"
' Apply your IronPDF license key
IronPdfGlobalConfig.getConfig().licenseKey = "Your license key"
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'export default async @function handler(req, res)
'{
'  try
'  {
'	const initHashids = New Hashids('IronPDF @Is Awesome @and Me is the salt', 8);
'	const f = req.query.f;
'	const l = initHashids.encode(f);
'	let content = "<h1>Demo Hashids and Generate PDF Using IronPDF</h1>" content+="<p>Input:"+f+"</p>";
'	content+="<p>HashID:"+l+"</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();
'  }
'}
VB   C#

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

import Head from "next/head";
import styles from "../styles/Home.module.css";
import React, { useState, useEffect } from "react";
import Hashids from 'hashids';
export default function Home() {
  const [text, setText] = useState("");
  const [etext, seteText] = useState("");
  const [hashids, setHashids] = useState(null);
  useEffect(() => {
    const initHashids = new Hashids('IronPDF Is Awesome and this is the salt', 8); 
    setHashids(initHashids);
  }, []);
  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf-hash?f=" + 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) => {
    seteText(hashids.encode(event.target.value));
    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 Hashids and Generate PDF Using IronPDF</h1>
        <p>
          <span>Enter Url To get Hashids and Convert to PDF:</span>{" "}
        </p>
        <p>
          HashID of input: {etext}
        </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 Hashids from 'hashids';
export default function Home() {
  const [text, setText] = useState("");
  const [etext, seteText] = useState("");
  const [hashids, setHashids] = useState(null);
  useEffect(() => {
    const initHashids = new Hashids('IronPDF Is Awesome and this is the salt', 8); 
    setHashids(initHashids);
  }, []);
  const generatePdf = async () => {
    try {
      const response = await fetch("/api/pdf-hash?f=" + 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) => {
    seteText(hashids.encode(event.target.value));
    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 Hashids and Generate PDF Using IronPDF</h1>
        <p>
          <span>Enter Url To get Hashids and Convert to PDF:</span>{" "}
        </p>
        <p>
          HashID of input: {etext}
        </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>
  );
}
Private Head As import
Private styles As import
'INSTANT VB TODO TASK: The following line could not be converted:
import React,
If True Then
	useState, useEffect
End If
from "react"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import Hashids from 'hashids'; export default @function Home() { const [text, setText] = useState(""); const [etext, seteText] = useState(""); const [hashids, setHashids] = useState(Nothing); useEffect(() => { const initHashids = New Hashids('IronPDF @Is Awesome @and Me is the salt', 8); setHashids(initHashids); }, []); const generatePdf = async() => { try { const response = await fetch("/api/pdf-hash?f=" + 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) => { seteText(hashids.encode(event.target.value)); 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 Hashids @and Generate PDF @Using IronPDF</h1> <p> <span> Enter Url @To @get Hashids @and Convert @to PDF:</span>{" "} </p> <p> HashID @of input: {etext} </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>); }
VB   C#

Code Explanation

  1. Taken input numbers from user through the input text box.
  2. Encode input number using HashID and display.
  3. When the user clicks Generate PDF, the input text is sent to a backend API, which encodes and generates a PDF document.

Output

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

PDF

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

IronPDF License

IronPDF.

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

Conclusion

Integrating Hashids into your React application is a practical approach to safeguarding sensitive data like database IDs or URLs. By using Hashids, you can ensure that identifiers remain secure while maintaining the ability to retrieve original data when required.

Whether you're building a small application or a complex enterprise system, Hashids offers a reliable solution to enhance data privacy and security in your React projects and excels at encoding incremented numbers into unique hashes. Hashids ensures that even repeating patterns in input numbers result in distinct, non-repetitive hashes, maintaining data integrity and security in applications.

IronPDF stands out as a robust and versatile library for node.js developers seeking comprehensive PDF generation, manipulation, and management capabilities within their applications. Whether you're building web applications, desktop software, or integrating PDF functionality into enterprise solutions.

< PREVIOUS
JsdomNPM (How It Works For Developers)
NEXT >
memcached npm (How It Works For Developers)

Ready to get started? Version: 2024.11 just released

Free npm Install View Licenses >