Categories
Javascript Tech

How to Print Long Item Names Correctly on an 80mm Thermal Printer with JavaScript

Printing receipts from a web application looks simple until you encounter a menu item with a long name.

A short item may print perfectly:

Butter Pav Bhaji       x1 ₹150

But a longer item can easily break an 80mm thermal receipt:

Paneer Cheese Pav Bhaji - Regular x1 ₹210

The quantity or price may move outside the printable area, text may be clipped, or the printer may wrap the line at an unexpected position.

I encountered this while generating a Kitchen Order Ticket (KOT) using JavaScript and browser printing.

The solution was not to reduce the font size or truncate menu item names.

Instead, I created a small fixed-width text formatter that:

  • wraps long item names automatically
  • avoids cutting words where possible
  • keeps quantity and price visible
  • keeps the total amount right-aligned
  • supports preparation options and notes
  • prints consistently on an 80mm thermal printer

Here’s how it works.


The Original Problem

The initial formatter was straightforward:

const LINE_WIDTH = 32;

const formatItem = (item: any) => {
    const total = item.price * item.qty;

    const left = `${item.name} x${item.qty}`;
    const right = `₹${total}`;

    const spacing =
        LINE_WIDTH - left.length - right.length;

    return (
        left +
        " ".repeat(Math.max(1, spacing)) +
        right
    );
};

For short menu items, this works well:

Butter Pav Bhaji       x1 ₹150

The formatter calculates the space between the item description and price and inserts enough spaces to align the amount.

The problem starts when the item name becomes longer than the available width.

For example:

Paneer Cheese Pav Bhaji - Regular x1 ₹210

There is no longer enough space for the item name, quantity, and price on the same line.

The calculation:

LINE_WIDTH - left.length - right.length

becomes negative.

Using:

Math.max(1, spacing)

prevents an invalid number of spaces, but it doesn’t solve the real problem: the text itself is too long for the receipt.


Why 80mm Thermal Printing Needs Special Handling

An 80mm paper roll does not necessarily provide 80mm of usable text space.

The actual printable area depends on several factors:

  • printer hardware margins
  • printer driver settings
  • browser print scaling
  • CSS padding
  • font family
  • font size
  • operating system print settings

For plain-text thermal printing, using a monospace font with a predictable character width makes formatting much easier.

In this example, I use:

const LINE_WIDTH = 32;

Thirty-two characters is deliberately conservative.

Some 80mm printers can fit more characters per line, but using a slightly smaller width makes the receipt more reliable across different printers and browser print configurations.


Step 1: Create Basic Receipt Helpers

First, define the receipt width and helpers for separators and centered text.

const LINE_WIDTH = 32;

const line = () => "-".repeat(LINE_WIDTH);

const center = (text: string) => {
    if (!text) return "";

    const space = Math.max(
        0,
        Math.floor(
            (LINE_WIDTH - text.length) / 2
        )
    );

    return " ".repeat(space) + text;
};

Now:

line();

produces:

--------------------------------

And:

center("SELF PICKUP");

produces approximately:

          SELF PICKUP

Because a monospace font is used later, each space has a predictable width.


Step 2: Create a Reusable Text-Wrapping Function

Next, we need a utility that can wrap long strings without cutting normal words in the middle.

const wrapText = (
    text: string,
    width: number
): string[] => {
    if (!text) return [];

    const words = text
        .trim()
        .split(/\s+/);

    const lines: string[] = [];

    let current = "";

    words.forEach((word) => {
        /*
         * Handle an individual word that is
         * longer than the entire available width.
         */
        if (word.length > width) {
            if (current) {
                lines.push(current);
                current = "";
            }

            for (
                let i = 0;
                i < word.length;
                i += width
            ) {
                lines.push(
                    word.slice(i, i + width)
                );
            }

            return;
        }

        const next = current
            ? `${current} ${word}`
            : word;

        if (next.length <= width) {
            current = next;
        } else {
            if (current) {
                lines.push(current);
            }

            current = word;
        }
    });

    if (current) {
        lines.push(current);
    }

    return lines;
};

For example:

wrapText(
    "Paneer Cheese Masala Pav Bhaji Regular",
    20
);

can produce:

Paneer Cheese Masala
Pav Bhaji Regular

Instead of:

Paneer Cheese Masala P
av Bhaji Regular

This makes printed receipts significantly easier to read.


Step 3: Format the Item While Reserving Space for Quantity and Price

The important part is that the item description should be flexible, while the quantity and price should remain readable.

For example, we want:

Paneer Cheese Pav    x3 ₹630
Bhaji

rather than:

Paneer Cheese Pav Bhaji x3 ₹
630

We can accomplish this by calculating how much space the metadata requires first.

const formatItem = (item: any) => {
    const qty = Number(
        item.qty || 0
    );

    const price = Number(
        item.price || 0
    );

    const total = price * qty;

    const name = String(
        item.name || ""
    ).trim();

    const meta = `x${qty} ₹${total}`;

    /*
     * Reserve enough room on the first
     * line for quantity and price.
     */
    const availableWidth = Math.max(
        10,
        LINE_WIDTH - meta.length - 1
    );

    const words = name.split(/\s+/);

    let firstLine = "";

    const remainingWords: string[] = [];

    for (
        let index = 0;
        index < words.length;
        index++
    ) {
        const word = words[index];

        const candidate = firstLine
            ? `${firstLine} ${word}`
            : word;

        if (
            candidate.length <=
            availableWidth
        ) {
            firstLine = candidate;
        } else {
            remainingWords.push(
                ...words.slice(index)
            );

            break;
        }
    }

    /*
     * Handle an unusually long first word.
     */
    if (
        !firstLine &&
        remainingWords.length
    ) {
        const word =
            remainingWords.shift()!;

        firstLine = word.slice(
            0,
            availableWidth
        );

        if (
            word.length >
            availableWidth
        ) {
            remainingWords.unshift(
                word.slice(
                    availableWidth
                )
            );
        }
    }

    /*
     * Calculate spacing between the item
     * description and quantity/price.
     */
    const spacing = Math.max(
        1,
        LINE_WIDTH -
            firstLine.length -
            meta.length
    );

    const output = [
        `${firstLine}${" ".repeat(
            spacing
        )}${meta}`,
    ];

    /*
     * Remaining item description can use
     * the entire width of subsequent lines.
     */
    if (remainingWords.length) {
        output.push(
            ...wrapText(
                remainingWords.join(" "),
                LINE_WIDTH
            )
        );
    }

    return output.join("\n");
};

Now long item names wrap without pushing the price outside the receipt.

For example:

Paneer Cheese Pav    x3 ₹630
Bhaji

Another item might produce:

Paneer Cheese Masala x1 ₹210
Pav Bhaji - Regular

And an even longer item remains safe:

Paneer Tikka Butter  x2 ₹640
Masala Special Family Size
with Extra Cheese

Step 4: Support Preparation Options and Notes

Kitchen tickets often contain more than the product name.

For example:

Paneer Butter Pav    x1 ₹190
Bhaji
  No Onion, Less Oil
  Note: Extra spicy

You can build the items section like this:

const itemsBlock = cart
    .map((item: any) =>
        [
            formatItem(item),

            item.prepOptions?.length
                ? "  " +
                  item.prepOptions.join(", ")
                : "",

            item.note
                ? "  Note: " + item.note
                : "",
        ]
            .filter(Boolean)
            .join("\n")
    )
    .join("\n");

This keeps additional kitchen instructions underneath their corresponding item.


Step 5: Right-Align the Total Amount

The same fixed-width technique can also create a cleaner total row.

Instead of:

TOTAL: ₹1710.00

we can print:

TOTAL:                  ₹1710.00

Create another formatter:

const formatTotal = (
    total: number | string
) => {
    const left = "TOTAL:";
    const right = `₹${total}`;

    const spacing = Math.max(
        1,
        LINE_WIDTH -
            left.length -
            right.length
    );

    return (
        left +
        " ".repeat(spacing) +
        right
    );
};

Then use:

formatTotal(total);

The result is:

--------------------------------
TOTAL:                  ₹1710.00
--------------------------------

This makes totals much easier to identify on a printed receipt.


Step 6: Build the Complete KOT

Here is a simplified version of the receipt builder.

This example uses dayjs for the timestamp.

View Complete Source Code section below in this page.


Step 7: Configure Browser Printing for 80mm Paper

Formatting the text correctly is only half of the solution.

The browser also needs to know that the output is intended for an 80mm thermal printer.

First, create a small HTML escape function.

const escapeHtml = (
    value: string
) => {
    return value
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
};

Escaping the receipt is important because item names, customer information, notes, and other values may contain characters that would otherwise be interpreted as HTML.

Then create the print function:

export const printReceipt = (
    text: string
) => {
    const printWindow =
        window.open("", "_blank");

    if (!printWindow) return;

    printWindow.document.write(`
        <!DOCTYPE html>

        <html>
            <head>
                <title>KOT</title>

                <style>
                    @page {
                        size: 80mm auto;
                        margin: 0;
                    }

                    * {
                        box-sizing: border-box;
                    }

                    html,
                    body {
                        margin: 0;
                        padding: 0;
                        width: 80mm;
                        background: #fff;
                    }

                    pre {
                        margin: 0;
                        padding: 4mm 3mm;
                        width: 80mm;

                        font-family:
                            "Courier New",
                            Courier,
                            monospace;

                        font-size: 12px;
                        line-height: 1.35;

                        white-space: pre-wrap;
                        overflow-wrap: break-word;

                        color: #000;
                    }

                    @media print {
                        html,
                        body {
                            width: 80mm;
                        }

                        pre {
                            width: 80mm;
                        }
                    }
                </style>
            </head>

            <body>
                <pre>${escapeHtml(text)}</pre>
            </body>
        </html>
    `);

    printWindow.document.close();

    printWindow.focus();

    setTimeout(() => {
        printWindow.print();
    }, 100);
};

The important CSS is:

@page {
    size: 80mm auto;
    margin: 0;
}

combined with:

font-family:
    "Courier New",
    Courier,
    monospace;

A monospace font is particularly important because the JavaScript formatter relies on characters having approximately equal visual widths.


Printing the KOT

Once the formatter and print function are ready, printing becomes straightforward:

const handlePrint = () => {
    if (!cart?.length) return;

    const text =
        buildThermalPrint({
            cart,
            customer,
            orderType,
            store,
            receiptNo,
        });

    printReceipt(text);
};

You can then connect it to a button:

<button
    type="button"
    onClick={handlePrint}
>
    Print KOT
</button>

Final Output

The resulting KOT can look like this:

         MY STORE Kitchen
--------------------------------
KOT No: 1790400901271
Date: 26/09/2026 11:05 AM
--------------------------------
          SELF PICKUP
--------------------------------
Paneer Cheese Pav    x3 ₹630
Bhaji - Regular

Paneer Butter Pav    x3 ₹570
Bhaji - Regular

Cheese Butter Pav    x1 ₹190
Bhaji - Regular

Paneer Cheese Masala x1 ₹210
Pav Bhaji - Regular

Butter Schezwan      x1 ₹110
Masala Dosa - Regular
--------------------------------
TOTAL:                  ₹1710.00
--------------------------------
Name: Guest Customer
Phone: 9876543210
--------------------------------
           Thank You

Long menu item names no longer push the quantity or price outside the receipt width.

The receipt also remains plain text, which makes it lightweight and suitable for thermal printing.


Why Not Just Use CSS word-wrap?

You could allow the browser to automatically wrap everything:

white-space: pre-wrap;
overflow-wrap: break-word;

But that alone doesn’t understand the structure of a receipt.

The browser might produce something like:

Paneer Cheese Pav Bhaji - Regular x3
₹630

or:

Paneer Cheese Pav Bhaji -
Regular x3 ₹630

That may technically fit, but it gives you less control over the kitchen ticket layout.

By formatting the text before printing, we explicitly tell the receipt:

  1. how wide a line can be
  2. where the item description should wrap
  3. where quantity should appear
  4. where price should appear
  5. how totals should align

CSS then handles the physical 80mm page.

The two approaches work together.


Why Use Plain Text Instead of an HTML Table?

HTML tables and CSS Grid can also produce excellent receipts.

However, plain-text formatting has some useful properties for thermal printing:

  • simple output
  • predictable layout
  • easy debugging
  • minimal CSS
  • easy copying and logging
  • works naturally with monospace printers
  • straightforward alignment

For more sophisticated receipts containing logos, multiple columns, QR codes, taxes, discounts, or complex invoice structures, an HTML-based layout may be preferable.

For a KOT, however, fixed-width text can be an effective solution.


Important: Character Width Is Not Physical Width

One thing to keep in mind is that:

const LINE_WIDTH = 32;

does not mean every 80mm printer can only print 32 characters.

Depending on the printer, font, DPI, and driver configuration, you may be able to use:

32
40
42

or even:

48

characters per line.

Start conservatively and test with the actual thermal printer.

For example:

const LINE_WIDTH = 32;

is safer than increasing the width until the text is almost touching both edges of the paper.

A small amount of unused horizontal space is usually preferable to clipped kitchen tickets.


Browser Printing Has Limitations

This implementation uses:

window.print();

That means the browser and operating system still control the final print process.

Depending on the environment, users may still need to select:

  • the correct thermal printer
  • 80mm paper size
  • appropriate margins
  • 100% print scale
  • header/footer disabled

For a web-based POS or restaurant ordering system, this approach works well when manual browser printing is acceptable.

If completely silent printing is required, a dedicated local printing solution or printer integration may eventually be necessary.


Final Thoughts

The key lesson is that thermal receipt formatting should not depend entirely on the browser deciding where text should wrap.

For a predictable 80mm KOT:

  1. use a monospace font
  2. define a maximum character width
  3. reserve space for quantity and price
  4. wrap long item names yourself
  5. right-align important numeric values
  6. explicitly configure the 80mm print page
  7. test against the physical printer

Instead of shrinking fonts or truncating menu item names, this approach lets the content naturally expand vertically while keeping the receipt width predictable.

That is usually exactly what you want from a thermal Kitchen Order Ticket.


Complete Source Code

The complete TypeScript implementation is available here:

View the 80mm Thermal KOT Printing Code → Coming soon this page.


Frequently Asked Questions

What line width should I use for an 80mm thermal printer?

There is no universal character count because it depends on the printer, font size, driver, and margins.

A value such as:

const LINE_WIDTH = 32;

is a conservative starting point.

Test the result using the actual printer before increasing it.

Why should I use a monospace font?

The formatter aligns content by counting characters and inserting spaces.

With a proportional font, characters have different visual widths, so:

TOTAL:                  ₹1710.00

may not align correctly.

A monospace font gives every character approximately the same width.

Can this work with a 58mm thermal printer?

Yes.

The same formatter can be used, but LINE_WIDTH, font size, and CSS width should be adjusted for the smaller paper size.

For example, you might start with a smaller line width and:

@page {
    size: 58mm auto;
}

The exact configuration should be tested against the target printer.

Can I print preparation options and kitchen notes?

Yes.

Because additional information is printed underneath the item, modifiers fit naturally:

Paneer Butter Pav    x1 ₹190
Bhaji
  No Onion, Less Oil
  Note: Extra spicy

This makes the same approach particularly useful for restaurant KOT printing.

Should I truncate long menu item names?

Usually, no.

For kitchen tickets, the full item name can be operationally important.

Allowing the description to wrap onto another line is generally safer than hiding part of the item name just to maintain a single-line layout.


If you’re building a restaurant POS, ordering application, or any web application that needs thermal printing, this fixed-width formatting approach provides a simple foundation that can later be extended for taxes, discounts, order numbers, QR codes, modifiers, and other receipt information.

Categories
AI & Technology Javascript Programming Technology, Web Development World in Motion

🚀 JavaScript Evolution: From Browser Scripting to Universal Runtime (2026 Deep Dive)

🧠 Introduction

JavaScript is no longer just a browser scripting language—it is now the backbone of modern software development. From powering interactive web pages in the 1990s to running full-scale distributed systems, JavaScript has evolved into a universal runtime shaping how applications are built and deployed.

In this deep dive, we explore:

  • How JavaScript has transformed over time
  • What major features and paradigms were introduced
  • How its ecosystem reshaped development
  • Where JavaScript is heading in the next decade

But beyond just evolution, JavaScript has fundamentally shifted its role in the tech ecosystem. It didn’t just grow—it repositioned itself as a universal runtime across platforms.
👉 Read deeper insight: JavaScript Didn’t Just Evolve — It Repositioned Itself


🕰️ Phase 1: The Early Days (1995–2005)

JavaScript was created in 1995 with a simple goal:
👉 Make web pages interactive.

Key Characteristics

  • Loosely typed
  • Prototype-based inheritance
  • Event-driven execution
  • Minimal tooling

Limitations

  • No modular architecture
  • Browser inconsistencies
  • Callback-heavy async patterns

At this stage, JavaScript was often underestimated and considered unreliable for serious engineering.


⚙️ Phase 2: Standardization with ES5 (2009)

The release of ECMAScript 5 brought stability and structure.

What Changed

  • Strict mode ("use strict")
  • Native JSON support
  • Functional array methods (map, filter, reduce)
  • Better object control

Why It Mattered

This era laid the foundation for scalable JavaScript applications and enabled cleaner, more predictable codebases.


🔥 Phase 3: ES6 – The Turning Point (2015)

ES6 was not just an update—it was a complete transformation.

This transformation marked the beginning of a deeper shift—not just in syntax, but in how JavaScript positioned itself in the software world.
👉 Explore the full perspective here: JavaScript Didn’t Just Evolve — It Repositioned Itself

Major Features Introduced

Block Scoping

let count = 0;
const MAX = 10;

Arrow Functions

const sum = (a, b) => a + b;

Classes (Cleaner OOP)

class User {
constructor(name) {
this.name = name;
}
}

Modules (Finally!)

export const api = {};
import { api } from './file.js';

Promises

fetch(url).then(res => res.json());

Destructuring

const { name } = user;

🚀 Impact of ES6

  • Enabled large-scale applications
  • Improved readability and maintainability
  • Shifted JavaScript toward modern engineering standards

🌍 JavaScript Beyond the Browser

⚡ Node.js Revolution

JavaScript expanded to the backend, enabling:

  • Server-side development
  • APIs and microservices
  • Real-time applications

👉 One language, full stack.

This moment defined JavaScript’s identity shift—from a frontend scripting tool to a cross-platform runtime environment.
👉 Detailed breakdown: JavaScript Didn’t Just Evolve — It Repositioned Itself


🎨 Frontend Framework Shift

Development moved from manual DOM handling to structured UI systems:

  • React → Component-driven architecture
  • Angular → Full ecosystem
  • Vue → Reactive simplicity

This introduced:

Declarative UI + state-driven design


⏳ Async Evolution: The Biggest Developer Pain Solved

Before (Callback Hell)

fs.readFile(file, (err, data) => {});

Promises

readFile(file).then(data => {});

Async/Await (Modern Standard)

async function load() {
const data = await readFile(file);
}

Result

  • Cleaner logic
  • Better debugging
  • Synchronous-like flow

🧩 TypeScript Influence (The Silent Takeover)

JavaScript itself didn’t become typed—but the ecosystem did.

Why TypeScript Won

  • Large app complexity
  • Need for type safety
  • Better tooling

Real Impact

  • Enterprise-level adoption
  • Reduced runtime errors
  • Strong IDE support

Today:

TypeScript is often the default, not optional.


⚡ Modern JavaScript (ES2018–2026)

JavaScript now evolves every year with incremental improvements.

Key Modern Features

Optional Chaining

user?.profile?.name

Nullish Coalescing

value ?? "default"

Top-Level Await

const data = await fetch(url);

Logical Assignment

x ||= 10;

BigInt

const big = 999999999999999999n;

🧠 The Real Power: JavaScript Ecosystem

The language is only part of the story.

Tooling Explosion

  • Bundlers: Webpack, Vite
  • Transpilers: Babel
  • Linters: ESLint
  • Formatters: Prettier

Runtime Expansion

  • Browser
  • Node.js
  • Deno
  • Bun

Cross-Platform Reach

  • Mobile → React Native
  • Desktop → Electron
  • Cloud → Serverless functions

🔄 Paradigm Shift Summary

AreaOld JavaScriptModern JavaScript
Code StructureScriptsModules
AsyncCallbacksAsync/Await
UIManual DOMComponent-based
RuntimeBrowser onlyEverywhere
TypingDynamicTyped (TS)

🔮 Where JavaScript Is Heading

1. Edge Computing

JavaScript is moving closer to users:

  • Faster response times
  • Distributed execution

2. WebAssembly Integration

JavaScript will act as a bridge for high-performance code:

  • Gaming
  • AI
  • Video processing

3. Type-Safe Future

  • TypeScript dominance
  • Possible native type support

4. AI + JavaScript

JavaScript is becoming the interface layer for AI systems:

  • Browser AI apps
  • Node.js AI orchestration
  • AI SDK ecosystems
This reinforces a critical idea: JavaScript isn’t just evolving—it’s strategically positioning itself at the center of modern computing.  
👉 Read the deeper analysis: JavaScript Didn’t Just Evolve — It Repositioned Itself

5. New Runtimes

Emerging tools like Bun and Deno are pushing:

  • Faster execution
  • Better developer experience

⚠️ Challenges Ahead

1. Ecosystem Overload

Too many tools, too many choices.

2. Complexity

Modern JS requires:

  • Build systems
  • Configurations
  • Dependency management

3. Backward Compatibility

JavaScript cannot break existing web apps—limiting radical changes.


🏁 Final Thoughts

JavaScript’s evolution is not just technical—it’s philosophical.

It has transformed into:

A universal language that connects frontend, backend, mobile, cloud, and AI systems.

The future of JavaScript is not about replacing it—but expanding it further into every layer of computing.

🔗 Recommended Deep Read

If you want to truly understand the strategic shift behind JavaScript’s dominance, don’t miss this:

👉 JavaScript Didn’t Just Evolve — It Repositioned Itself

This article breaks down how JavaScript moved from a simple scripting language to becoming the backbone of modern development ecosystems.

Categories
Javascript Learning Learning Tech

Building & Publishing a Cross-Framework React Hook — 📝react-usedrafty

Prevent accidental form data loss and enhance user experience — one small, powerful hook at a time.

Introduction

In this article, we’ll walk through the journey of creating, enhancing, testing, and publishing a universally compatible React hook for saving form drafts in the browser: react-usedrafty.

Our goal was to:

  • Build a plug-and-play solution for auto-saving and restoring form state.
  • Make it framework-agnostic, working with React, Next.js, and React Router projects.
  • Keep it lightweight with zero dependencies.
  • Add real-world features like route-change warnings and customizable leave prompts.

Step 1 — Hook Requirements

From the initial idea, these requirements were set:

  • Auto-save form data to localStorage or sessionStorage.
  • Restore data on page reload.
  • Warn the user before leaving if there are unsaved changes.
  • Support Next.js and React Router route change detection.
  • Provide clean API and TypeScript types.

Step 2 — Core Hook Implementation

We built the useDrafty hook in TypeScript, then configured the build to export both ESM and CJS formats for maximum compatibility.

Key features in the core:

  • Storage type selection (local / session).
  • Debounce saving.
  • Restore on mount.
  • Dirty-state detection.
  • Configurable warnOnLeave with custom messages.
  • Route change prevention via injected router instance.

Example API usage:

tsxCopyEdituseDrafty("contact-form", formState, setFormState, {
  storage: "local",
  delay: 1000,
  warnOnUnload: true,
  unloadMessage: "You have unsaved changes!",
  router: nextRouterOrReactRouter,
  onRestore: (data) => console.log("Draft restored:", data)
});

Step 3 — Adding Router Awareness

We avoided hard dependencies on Next.js or React Router by letting the user pass their router object.

Internally:

  • For Next.js, we hook into router.events.on("routeChangeStart", cb).
  • For React Router, we watch location changes.

This way:

  • No extra packages are required.
  • The hook works without any router if that feature is not needed.

Step 4 — Packaging for the World

We ensured compatibility by:

  • Targeting ESNext but compiling to both ESM & CJS.
  • Generating .d.ts files for TypeScript users.
  • Writing a package.json with proper "exports" mapping.

Example "exports":

jsonCopyEdit"exports": {
  ".": {
    "import": "./dist/index.mjs",
    "require": "./dist/index.js",
    "types": "./dist/index.d.ts"
  }
}

We also configured:

  • npm run build → Generates ESM, CJS, DTS.
  • .npmignore → Excludes /example from the package.

Step 5 — Local Testing

We:

  • Added an /example folder using Vite & React for quick testing.
  • Made sure the package works by linking locally via:
bashCopyEditnpm link
npm link react-usedrafty
  • Verified in plain React, Next.js, and React Router apps.

Step 6 — Publishing to npm

Version management steps:

bashCopyEdit# Update version
npm version patch  # or minor/major

# Publish
npm publish --access public

💡 Mistake: If you bump the wrong version, you can revert with:

bashCopyEditnpm version 1.2.2 --no-git-tag-version

Step 7 — Documentation

We created a detailed README including:

  • Feature list.
  • Install instructions.
  • Basic & advanced usage.
  • API reference.
  • Changelog with new features (e.g., warnOnUnload, router support).

Step 8 — What’s New in the Latest Version

From this latest dev cycle, we added:

  • Router-aware leave warnings (Next.js + React Router).
  • Custom restore callback onRestore.
  • Universal build that works across major JS environments.
  • Debounce control for save frequency.
  • Clear API for dirty-state detection (isDirty flag).

Conclusion

By following this process, we built a hook that:

  • Works in React, Next.js, CRA, and other environments.
  • Handles both browser unload and in-app route changes.
  • Ships with full TypeScript types.
  • Has local examples for quick testing.
  • Is ready for npm publication with a clean API and docs.

This approach can be applied to any React utility you want to share with the community while keeping it framework-flexible.


Made with ❤️& Fire in heart
PRs and feedback welcome!

Categories
Blog Javascript Learning

Solution: TypeError: Failed to construct ‘URL’: Invalid URL

Hello,

If you are facing error :


Unhandled Runtime Error
TypeError: Failed to construct 'URL': Invalid URL
Failed to construct ‘URL’ : Invalid URL in your nextjs app

And you already have following loader ‘imgix’ settings in your next.config.js file

images: {
    // loader and path setting for android build to load nextjsimage and also on web on certain scenarios!
    loader: 'imgix',
    path: '/', // Remove the path prefix for production images
    domains: [
      'xxx.com',
      '*.xxx.com',
      'aaa.xxx.com',
      'via.placeholder.com',
    ],
}

To fix this the solution provided here worked out well!

Code snippet solution: source page stackoverflow

const loaderProp =({ src }) => {
    return src;
}

<Image
      src={currentImage.imageurl}
      alt={currentImage.imageurl} 
      layout="fill"
      className={styles.imageSize} 
      loader={loaderProp}
/>

we just need to add loader prop to the Image tag of next.js component and passdown the callback function which resolves the error above, voila!

Hope this also help you if you are facing this solution in your next.js application.

happy learning!

Categories
Javascript Learning Tech

Function getStaticPaths, How to create paths in getStaticProps function If you have no access to create paths in getStaticPaths, NEXTJS

Hello,

Hope this is very interesting question of scenario you might be facing to solve with next js and

  • when you don’t want to use “function getServerSideProps” to pass dynamic (data as) props to the page components
  • when you don’t want too make a extra API calls to generate the paths for products or whatever list of thing you are creating in “function getStaticPaths”

Here is the quick things we need to work out to work this out of box for specially the scenario were are showing product detail view page which is of route like in Nextjs as “page/product/[id].js“

First in function getStaticPaths() we just need to do this and pass fallback as “true” as we our dynamic path is not pre-rendered!

export async function getStaticPaths() {
    // Empty array since paths will be dynamically created in getStaticProps
    return {
        paths: [],
        fallback: true, // Set to true if there are dynamic paths that are not pre-rendered !! 
    };
};

Next, we need to edit our “getStaticProps” function and then voila;


export async function getStaticProps({ params }) {
    const product = await getProduct(params && params.id);
    if (!product) {
        return {
            redirect: {
                destination: '/',
                permanent: false,
            },
        }
    }

    return {
        props: {
            product,
            error: resp.error ? true : false
        }
    };
}

Boom you are done, and just use those props in your page component like



return (<PhotoProvider
        key={'photoprovider-key-' + product?.id}
        speed={() => 600}
        easing={(type) => (type === 2 ? '' : 'cubic-bezier(.25, 1, .30, 1)')}>

/*...other codes*/
</PhotoProvider>

you will find you page up and working, fine!

Hope this simple steps helps to solve our complex situations arises in the development work of software building on planet earth!

I would also like to the above situation, why we can’t just do the same thing simply with getServerSideProps in single function, I am facing the issue to build using next build && next export for android package, as dynamics cannot be rendered as html files due to getServerSideProps sitting in between, and also as per the Next JS docs we can’t do anything what I have found of my learnings.

Happy Learning! Thanks for reading.

Keep coding & Develop Wonderful.

To Follow help out to know: uidevwork

Categories
Javascript Learning Tech

What is forwardRef and how its helps in react?

Hello, lets quickly take a review on React forwardRef, what it in actual,

In React, the forwardRef function is a utility that allows you to pass a ref through a component to one of its children. It’s commonly used when you need to access the underlying DOM node or React component instance of a child component from the parent component.

When you create a component using functional components in React, you can use the useRef hook to create a ref object. This ref object can then be passed as a prop to child components. However, when you pass the ref as a prop to a child component, React does not automatically pass it down to the underlying DOM element or custom component. This is where forwardRef comes into play.

By using forwardRef, you can create a component that accepts a ref and forwards it to one of its children. Here’s an example:

const ChildComp = React.forwardRef((props, ref) => {
  // Use the ref object to access the underlying DOM node or component instance
  return <input ref={ref} />;
});

const ParentComp = () => {
  const inputRef = React.useRef(null);

  const handleClick = () => {
    // Access the input element using the ref
    if (inputRef.current) {
      inputRef.current.focus();
    }
  };

  return (
    <div>
      <ChildComponent ref={inputRef} />
      <button onClick={handleClick}>Focus Input</button>
    </div>
  );
};

In the example above, the ChildComponent uses forwardRef to forward the ref prop to the <input> element. In the ParentComponent, a ref is created using the useRef hook and passed to ChildComponent using the ref prop. This allows the ParentComponent to access the input element and call the focus method when the button is clicked.

By using forwardRef, helps to bridge the gap between functional components and the imperative DOM or component operations that sometimes require direct access to child component element.

Note here we are accessing child’s component dom node not child component here as ref object, i.e can be consider as subtle difference to understand for our mind.

Hope this helps to clear out the basic concept behind using forwardRef in React.

Happy Learning!

Categories
Javascript Learning Tech

How to fix nextjs appending http://localhost:3000/_next/image? to the image srcset how to remove for production build for images?

Hello,

Welcome to the question and for the search, facing this issue? lets quickly see how we can fix this, with and in next.config.js file.

In Next.js, when using the next/image component, the src attribute is automatically transformed to a URL that goes through the Next.js image optimization pipeline. During development, this URL may include http://localhost:3000/_next/image? to indicate the local development server.

However, for production images, you can configure Next.js to remove the http://localhost:3000/_next/image? prefix. Here’s how you can achieve that:

Create a custom loader for Next.js images:

  • Open next.config.js and add the following code:
    • module.exports = {
    • images: {
      • loader: 'imgix',
      • path: '', // Remove the path prefix for production images
    • }, };
  • This configuration sets the loader option to use the imgix loader, which removes the http://localhost:3000/_next/image? prefix. The path option is set to an empty string, this will leave the prefix for image urls and left blank

Now you can easily build your project and test to images are loading fine with absolute url path if applied so.

Hope this help to solve the issue.

Happy Learning!

Categories
Javascript Learning

How to fix Uncaught TypeError: Cannot assign to read only property ‘0’ of object occurring in JavaScript?

Hello,

This type error mostly get in scenario when you try to sort the readyonly data array.

For me this was occoured when I tried to sort the direct result from my GraphQL query response data like below:

const sortedData = data.bhangarwalas.sort((a, b) => a?.firstname > b?.firstname ? 1 : -1);

In above, data.bhangarwalas is graphql query response results which is readonly in nature as response.

To fix this issue the solution is quick fix for which I have too google to know the result!

Error Screenshot Uncaught TypeError: Cannot assign to read only property ‘0’ of object ‘[object Array]’

Here is the quick solution:

const sortedData = [...data.bhangarwalas];
      sortedData.sort((a, b) => a?.firstname > b?.firstname ? 1 : -1);

In code above, We need to clone or you in other words, copying the “data.bhangarwalas” into new array variable and then over that variable, we need to perform sorting operation, which results us right response.

Hope this help you to solve the quick error or to know what scenario this type of error is generated.

Thanks for reading.

Happy learning!

Categories
Javascript Learning Tech

What to do when you get nextjs error (Module not found: Error: Can’t resolve ‘private-next-pages/’ in ‘/vercel/path0’) on vercel/nextjs deployment?

Hello,

If you too facing this error : Module not found: Error: Can’t resolve ‘private-next-pages/’ in ‘/vercel/path0’

while deploying your NextJs project over Vercel platform, please follow what solution and mistake I was doing.

Error Screenshot of error occurring from the NextJs Project deployment on vercel platform.

As, I tried to debug this error by right away check the the next in the log highlighted (in screenshot above) recommending to following alias rule to be set if you have touched you next.config.js file with any webpack settings.

In my case I did have to touched the next.config.js file and so I have add the same lines of code recommend in the follow link of Next.js doc

https://nextjs.org/docs/messages/invalid-resolve-alias

But for me still I didn’t found the right solution, because was in the naming of folder under nextjs project.

Basically, I was loading the static content into the dynamic route in Nextjs (Like example reference here).

What I have missed was the name of the folder under pages directory I have created named as “learn” it should be similar to name “posts” as created one at root level of the project to hold the “.md” or “.html” file content to pass down to dynamic route page which will be under /pages/posts/[id].js

Sharing here screenshot of the directory where the naming was a mistake

Here highlighted “learn” folder should be same as “posts” below

After renaming the folder name “learn” to “posts” the error went off and found my deployment working successfully.

Hope this small mistake tip help you to solve this problem.

If you have found any mistake in the post. Please don’t hesitate to hit me on my email jat@doableyo.com to rectify.

Enjoyed reading this? How about sharing with your friends or in groups, this would help!

Thanks, Happy Learning!

Categories
Javascript Tech

What is Event Loop & Micro and Macro Tasks in JavaScript?

Hello,

The basic concept behind the event loop working in Javascript engine!

Event Loop is a mechanism in JavaScript that handles asynchronous tasks in a non-blocking way. When JavaScript code is executed, it is run inside an event loop, which continuously checks if there are any tasks to be executed in the queue. The event loop is responsible for running the tasks in the queue, and it does this in a specific order.

The Event Loop in JavaScript has two main components: the Call Stack and the Callback Queue. The Call Stack is responsible for keeping track of the execution of the synchronous code. When a function is called, it is added to the top of the call stack, and when the function returns, it is removed from the top of the call stack.

The Callback Queue, on the other hand, is responsible for keeping track of the asynchronous tasks. When an asynchronous task is completed, it is added to the Callback Queue. The event loop continuously checks the Callback Queue to see if there are any tasks that can be executed. If there is a task, it is moved to the Call Stack, where it is executed.

Microtasks and Macrotasks are two types of tasks in JavaScript that are executed by the event loop.

Microtasks are tasks that are executed immediately after the current task has completed. Microtasks are executed before the next rendering of the web page, which means that they have a higher priority than Macrotasks. Some examples of Microtasks include Promises, MutationObserver, and process.nextTick in Node.js.

Macrotasks, on the other hand, are tasks that are executed after all the Microtasks have been executed. Macrotasks include tasks such as setTimeout, setInterval, and I/O operations in Node.js.

In summary, the Event Loop in JavaScript is responsible for handling asynchronous tasks in a non-blocking way. The Event Loop has two main components, the Call Stack and the Callback Queue. Microtasks and Macrotasks are two types of tasks that are executed by the event loop, and they have different priorities. Microtasks are executed before Macrotasks and are used for tasks that need to be executed immediately after the current task has completed, while Macrotasks are used for tasks that can be executed at a later time.

Source: AI Interaction Channels

Happy Learning!