Building a Production-Level POS System with Node.js and Next.js

If you have ever stood behind a shop counter on a busy Saturday, you already know the real requirements of a point of sale system. The scanner has to beep and the item has to appear instantly. The receipt has to print. The Wi-Fi will drop at the worst moment, and the queue will not wait for it to come back. And at closing time, the cash in the drawer has to match what the system says, to the last rupee.

That is why a POS is one of my favourite projects for learning production engineering. On the surface it is “a cart and a pay button”. Underneath, it forces you to deal with money arithmetic, concurrency, offline sync, hardware, permissions and auditing, all in one app.

This post is the introduction to the Eskillsfy POS series. We will go through the architecture, the core modules, the data model and the stack, with real code along the way. Later posts go deep on each module.

What “production level” actually means for a POS

Before writing any code, it helps to be honest about what separates a tutorial POS from one a shop can run its business on:

  • Speed at the counter. Adding an item after a scan should feel instant, which means under 100 ms. Nobody wants a loading spinner between beeps.
  • It keeps selling when the internet is down. A shop cannot close because the router restarted. Sales must be stored locally and synced later, without duplicates.
  • Money is never wrong. No floating point rounding errors, no double charges, no “the total changed after the bill printed”.
  • Stock stays truthful. Two counters selling the last unit of a product at the same time must not leave you with -1 in stock and no idea why.
  • Everything is auditable. Every discount, void, refund and drawer opening is recorded with who did it and when.
  • Roles and permissions. A cashier can sell. A supervisor can approve a big discount. Only the owner sees profit reports.
  • Shift closing. At the end of the day the cashier counts the drawer, the system shows the expected amount, and any difference is recorded.

If your design covers these seven points, you are building something real. Everything below is organised around them.

The high-level architecture

Here is the shape of the system we will build:

┌──────────────────────────────┐       ┌──────────────────────────────┐
│  POS Terminal (Next.js PWA)  │       │  Back Office (Next.js)       │
│  - Checkout screen           │       │  - Products & pricing        │
│  - IndexedDB (local store)   │       │  - Stock & purchases         │
│  - Sync queue                │       │  - Users & roles             │
│  - Barcode + receipt printer │       │  - Reports                   │
└──────────────┬───────────────┘       └──────────────┬───────────────┘
               │  HTTPS (REST + idempotency keys)     │
               └──────────────────┬───────────────────┘
                                  ▼
                   ┌──────────────────────────────┐
                   │  Node.js API (Express)       │
                   │  - Auth (JWT + PIN login)    │
                   │  - Catalog, Sales, Stock     │
                   │  - Shifts, Reports           │
                   └───────┬──────────────┬───────┘
                           ▼              ▼
                    ┌────────────┐  ┌────────────┐
                    │  MongoDB   │  │  Redis     │
                    │ (replica   │  │ (cache,    │
                    │   set)     │  │  queues)   │
                    └────────────┘  └────────────┘

There are two frontends on purpose. The terminal is the screen the cashier uses all day. It is optimised for speed, keyboard and scanner input, and offline use. The back office is where the owner manages products, stock, staff and reports. Both talk to the same Node.js API, but they have very different needs, so we keep them as separate apps (or at least separate route groups in one Next.js project).

The stack and why each piece is there

Layer Choice Why
Terminal UI Next.js (App Router) as a PWA Installable on a counter PC or tablet, works offline with a service worker
Local storage IndexedDB (via Dexie) Holds the product catalog and unsynced sales on the device
API Node.js + Express + TypeScript Simple, fast, and the same language as the frontend
Database MongoDB (replica set) Flexible product documents, and multi-document transactions for sales
Cache / jobs Redis + BullMQ Caching the catalog, background jobs like reports and email receipts
Auth JWT for devices, short PIN for cashiers A terminal stays logged in, cashiers switch quickly with a PIN
Validation Zod One schema shared by the API and the frontend

One important note on MongoDB: you need a replica set (even a single-node one in development) to use transactions. A sale touches several documents at once (the sale, the stock levels, the shift totals), and we want all of those changes to succeed or fail together.

The core modules

A POS breaks down nicely into modules. Each one becomes a folder in the API and a set of screens in the frontend.

  1. Auth and roles. Owner, manager, cashier. Device registration so only known terminals can sell.
  2. Catalog. Products, variants (size, colour), barcodes, categories, tax rates and prices.
  3. Cart and checkout. Scanning, quantity changes, discounts, holds (“park this bill”), and the final payment.
  4. Payments. Cash, card, UPI or wallet, and split payments (part cash, part card).
  5. Stock. Stock per store, stock movements, purchases from suppliers, adjustments and low-stock alerts.
  6. Receipts. Thermal printer output, plus an optional digital receipt by email or SMS.
  7. Offline sync. The local queue on the terminal and the idempotent sync endpoint on the server.
  8. Shifts and cash drawer. Open shift with a float, cash in and out, close shift with a counted amount.
  9. Returns and refunds. Linked to the original sale, with stock going back in.
  10. Reports. Daily sales, sales by product and cashier, tax summary, and profit.

We will not build all ten in one post. Today we focus on the foundation: the data model, a correct sale transaction, and offline sync, because every other module leans on these three.

The data model

Here are the main collections. I am showing them as TypeScript types because that is how we will share them between the API and the frontend.

// All money is stored as integers in the smallest unit (paise / cents).
type Money = number;

interface Product {
  _id: string;
  storeId: string;
  name: string;
  sku: string;
  barcodes: string[];        // one product can have several barcodes
  categoryId: string;
  price: Money;              // selling price, tax inclusive or exclusive per store setting
  cost: Money;               // purchase cost, used for profit reports
  taxRateBps: number;        // tax in basis points: 1800 = 18%
  trackStock: boolean;
  active: boolean;
  updatedAt: Date;
}

interface StockLevel {
  _id: string;
  storeId: string;
  productId: string;
  quantity: number;
}

interface StockMovement {
  _id: string;
  storeId: string;
  productId: string;
  change: number;            // -2 for a sale of 2 units, +10 for a purchase
  reason: "sale" | "refund" | "purchase" | "adjustment" | "transfer";
  refId: string;             // the sale, purchase or adjustment that caused it
  userId: string;
  createdAt: Date;
}

interface Sale {
  _id: string;
  clientId: string;          // id generated on the terminal, used for idempotency
  number: string;            // human receipt number, e.g. "S1-000245"
  storeId: string;
  terminalId: string;
  shiftId: string;
  cashierId: string;
  lines: SaleLine[];
  subtotal: Money;
  discountTotal: Money;
  taxTotal: Money;
  total: Money;
  payments: Payment[];
  status: "completed" | "refunded" | "partially_refunded" | "void";
  createdAt: Date;           // time on the terminal when the sale happened
  syncedAt: Date;            // time it reached the server
}

interface SaleLine {
  productId: string;
  name: string;              // snapshot, so old receipts never change
  unitPrice: Money;          // snapshot of the price at the time of sale
  quantity: number;
  discount: Money;
  taxRateBps: number;
  lineTotal: Money;
}

interface Payment {
  method: "cash" | "card" | "upi" | "wallet";
  amount: Money;
  reference?: string;        // card or UPI transaction id
}

interface Shift {
  _id: string;
  terminalId: string;
  cashierId: string;
  openingFloat: Money;
  expectedCash: Money;       // updated with every cash sale, refund and payout
  countedCash?: Money;
  difference?: Money;
  openedAt: Date;
  closedAt?: Date;
}

A few decisions in here are worth calling out, because they are the ones beginners usually get wrong:

Money is an integer. In JavaScript, 0.1 + 0.2 is 0.30000000000000004. That is fine for a chart, and a disaster for a till. We store ₹249.50 as 24950. All arithmetic happens on integers, and we only format to a decimal string when we display or print.

Sale lines are snapshots. The line stores the product name, unit price and tax rate as they were at the moment of sale. If the owner changes the price tomorrow, last week’s receipts and reports must not change. Never compute old sales by joining to the current product.

Stock is a number plus a history. StockLevel gives you a fast current quantity. StockMovement tells you why it is that number. When a shop owner asks “where did my 12 units go?”, the movement log is the answer. It is also how you rebuild stock if something ever goes wrong.

The terminal generates the sale id. clientId is a UUID created on the device before the sale is even sent. This is the key to safe offline sync, which we will see in a moment.

Getting the totals right

Totals are calculated in one shared function used by both the terminal and the server. The terminal uses it to show the total instantly. The server runs it again and never trusts the totals the client sends.

// packages/shared/src/totals.ts
export function calculateTotals(lines: SaleLineInput[], taxInclusive: boolean) {
  let subtotal = 0, discountTotal = 0, taxTotal = 0;

  const computed = lines.map((l) => {
    const gross = l.unitPrice * l.quantity;
    const net = gross - l.discount;

    // Integer maths only. Round tax once per line, half up.
    const tax = taxInclusive
      ? net - Math.round((net * 10000) / (10000 + l.taxRateBps))
      : Math.round((net * l.taxRateBps) / 10000);

    const lineTotal = taxInclusive ? net : net + tax;

    subtotal += gross;
    discountTotal += l.discount;
    taxTotal += tax;

    return { ...l, lineTotal };
  });

  const total = computed.reduce((sum, l) => sum + l.lineTotal, 0);
  return { lines: computed, subtotal, discountTotal, taxTotal, total };
}

Putting this in a shared package (a small workspace inside a monorepo) means the receipt preview on the screen and the saved sale on the server can never disagree.

The sale transaction on the server

This is the heart of the POS. When a sale arrives, the server has to do several things as one unit: check it has not seen this sale before, recalculate totals, decrease stock, write stock movements, update the shift’s expected cash, and save the sale.

// api/src/modules/sales/sales.service.ts
import { startSession } from "mongoose";
import { calculateTotals } from "@eskillsfy/shared";

export async function recordSale(input: SaleInput, ctx: RequestContext) {
  // 1. Idempotency: if this terminal already sent this sale, return it.
  const existing = await Sale.findOne({ clientId: input.clientId });
  if (existing) return existing;

  const session = await startSession();
  try {
    let sale;
    await session.withTransaction(async () => {
      // 2. Load current products and recalculate everything server side.
      const products = await Product.find(
        { _id: { $in: input.lines.map((l) => l.productId) }, storeId: ctx.storeId },
        null,
        { session }
      );
      const lines = buildLinesFromProducts(input.lines, products); // snapshots name, price, tax
      const totals = calculateTotals(lines, ctx.store.taxInclusive);

      assertPaymentsCoverTotal(input.payments, totals.total);

      // 3. Decrease stock and log each movement.
      for (const line of totals.lines) {
        await StockLevel.updateOne(
          { storeId: ctx.storeId, productId: line.productId },
          { $inc: { quantity: -line.quantity } },
          { session, upsert: true }
        );
        await StockMovement.create(
          [{ storeId: ctx.storeId, productId: line.productId, change: -line.quantity,
             reason: "sale", refId: input.clientId, userId: ctx.userId }],
          { session }
        );
      }

      // 4. Update the cash expected in the drawer.
      const cashPaid = sumCash(input.payments) - (input.changeGiven ?? 0);
      await Shift.updateOne(
        { _id: input.shiftId, closedAt: { $exists: false } },
        { $inc: { expectedCash: cashPaid } },
        { session }
      );

      // 5. Save the sale with a sequential receipt number.
      const number = await nextReceiptNumber(ctx.terminalId, session);
      [sale] = await Sale.create(
        [{ ...input, ...totals, number, storeId: ctx.storeId, syncedAt: new Date() }],
        { session }
      );
    });
    return sale;
  } catch (err) {
    // Two copies of the same sale raced each other: the unique index stopped
    // the second insert, so hand back the one that won.
    if (err.code === 11000) return Sale.findOne({ clientId: input.clientId });
    throw err;
  } finally {
    await session.endSession();
  }
}

Two details make this safe in production:

  • There is a unique index on clientId. Even if two copies of the same request race each other, only one can be inserted. The other fails, and we return the existing sale instead of an error.
  • Stock is allowed to go negative. That surprises people. But think about the shop: if a customer is standing at the counter with the item in their hand, the item exists, whatever the database thinks. Blocking the sale only frustrates the cashier. Instead we allow it, flag the product in a “negative stock” report, and let the manager fix the count. Real POS systems work this way.
// Indexes that matter
db.sales.createIndex({ clientId: 1 }, { unique: true });
db.sales.createIndex({ storeId: 1, createdAt: -1 });
db.products.createIndex({ storeId: 1, barcodes: 1 });
db.stocklevels.createIndex({ storeId: 1, productId: 1 }, { unique: true });

Offline first: selling without the internet

This is the module that turns a demo into a real product. The idea is simple: the terminal never waits for the server to finish a sale. It saves the sale locally, prints the receipt, and syncs in the background.

On the terminal we keep two things in IndexedDB: a copy of the catalog (so scanning works offline) and an outbox of sales that have not reached the server yet.

// terminal/src/lib/db.ts
import Dexie, { Table } from "dexie";

class PosDB extends Dexie {
  products!: Table<Product, string>;
  outbox!: Table<OutboxSale, string>;

  constructor() {
    super("eskillsfy-pos");
    this.version(1).stores({
      products: "_id, *barcodes, sku, name",
      outbox: "clientId, status, createdAt",
    });
  }
}
export const db = new PosDB();

Completing a sale writes to the outbox first, then tries to sync:

// terminal/src/lib/checkout.ts
export async function completeSale(cart: Cart, payments: Payment[]) {
  const sale: OutboxSale = {
    clientId: crypto.randomUUID(),
    ...calculateTotals(cart.lines, settings.taxInclusive),
    payments,
    shiftId: session.shiftId,
    createdAt: new Date().toISOString(),
    status: "pending",
    attempts: 0,
  };

  await db.outbox.put(sale);   // safe on disk before anything else
  printReceipt(sale);          // the customer is not kept waiting
  void syncOutbox();           // fire and forget
  return sale;
}

export async function syncOutbox() {
  if (!navigator.onLine) return;
  const pending = await db.outbox.where("status").equals("pending").sortBy("createdAt");

  for (const sale of pending) {
    try {
      const res = await api.post("/sales", sale, {
        headers: { "Idempotency-Key": sale.clientId },
      });
      await db.outbox.update(sale.clientId, { status: "synced", number: res.data.number });
    } catch (err) {
      await db.outbox.update(sale.clientId, { attempts: sale.attempts + 1 });
      break; // keep order; retry later
    }
  }
}

window.addEventListener("online", syncOutbox);
setInterval(syncOutbox, 30_000);

Because every sale carries its own clientId, retries are completely safe. If the request reached the server but the response got lost, the next retry returns the already saved sale instead of creating a second one. That one idea, idempotency keys generated on the client, solves most of the scary problems in offline sync.

A practical tip: when you are debugging the sync, export the outbox from the browser console and paste it into the Eskillsfy JSON formatter. Seeing a pretty-printed queue of pending sales, with their attempts and timestamps, makes it much easier to spot the one that is stuck.

Keeping the catalog fresh

The terminal also needs product updates. We do a delta sync: the terminal remembers the last updatedAt it saw and asks only for products changed since then.

// GET /catalog/changes?since=2026-11-22T10:15:00Z
router.get("/catalog/changes", auth("terminal"), async (req, res) => {
  const since = new Date(String(req.query.since ?? 0));
  const products = await Product.find({ storeId: req.ctx.storeId, updatedAt: { $gt: since } })
    .sort({ updatedAt: 1 })
    .limit(1000)
    .lean();
  res.json({ products, serverTime: new Date().toISOString() });
});

Notice we soft-delete products (active: false) instead of removing them. A deleted document cannot show up in a “changed since” query, so the terminal would never learn it is gone.

Barcode scanning that feels instant

Most USB and Bluetooth barcode scanners act like a keyboard. They “type” the code very quickly and press Enter. So you do not need a special driver; you need a listener that can tell a scanner from a human typing.

// terminal/src/hooks/useBarcodeScanner.ts
export function useBarcodeScanner(onScan: (code: string) => void) {
  useEffect(() => {
    let buffer = "";
    let last = 0;

    const onKey = (e: KeyboardEvent) => {
      const now = performance.now();
      if (now - last > 50) buffer = "";   // humans type slower than 50 ms per key
      last = now;

      if (e.key === "Enter" && buffer.length >= 6) {
        onScan(buffer);
        buffer = "";
      } else if (e.key.length === 1) {
        buffer += e.key;
      }
    };

    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [onScan]);
}

The lookup itself goes to IndexedDB, not the network, which is why it feels instant:

const product = await db.products.where("barcodes").equals(code).first();

For the product thumbnails shown on the checkout grid, keep the images tiny. A counter PC with 500 products and full-size photos will feel slow. Run them through an image compressor before upload (the Eskillsfy image tools are being built for exactly this) and serve small WebP thumbnails to the terminal.

Shifts and the cash drawer

Shift closing is where trust in the system is won or lost. The flow is:

  1. Open shift. The cashier enters the opening float, for example ₹2,000 in change.
  2. During the shift. Every cash sale adds to expectedCash. Every cash refund and payout (paying the milk delivery from the drawer) subtracts from it, with a reason.
  3. Close shift. The cashier counts the drawer without seeing the expected amount first, and types the counted total.
  4. Reconcile. The system records the difference. Small differences are normal; big ones need a manager to review.

Hiding the expected amount during the count is a small UX choice with a big effect. If cashiers can see the number, they tend to “find” it.

Roles and permissions

Keep permissions as a list of actions, not just a role name, so you can adjust them per shop:

const permissions = {
  cashier:  ["sale.create", "sale.hold", "shift.open", "shift.close"],
  manager:  ["sale.create", "sale.void", "discount.override", "refund.create",
             "stock.adjust", "report.view"],
  owner:    ["*"],
} as const;

export const requirePermission = (action: string) => (req, res, next) => {
  const allowed = permissions[req.user.role];
  if (allowed.includes("*") || allowed.includes(action)) return next();
  return res.status(403).json({ error: "Not allowed", action });
};

On the terminal, a sensitive action like a large discount shows a “manager approval” dialog. The manager types their PIN, the API checks their permission, and the approval is stored on the sale line with the manager’s id. That is your audit trail.

Receipts

Most thermal printers speak ESC/POS. You can print from the browser through WebUSB on supported devices, or through a tiny local print service on the counter PC. Either way, build the receipt from the saved sale, never from the live cart, so a reprint always matches the original.

Some older printers and legacy billing systems export or accept data as XML. If you are migrating a shop from an old system, the Eskillsfy XML ⇄ JSON converter is handy for turning those exports into JSON you can import into the new catalog.

Project structure

Here is how the repository is laid out. It is a monorepo so the shared types and totals logic live in one place.

eskillsfy-pos/
├── apps/
│   ├── api/                 # Node.js + Express
│   │   └── src/modules/
│   │       ├── auth/
│   │       ├── catalog/
│   │       ├── sales/
│   │       ├── stock/
│   │       ├── shifts/
│   │       └── reports/
│   ├── terminal/            # Next.js PWA for the counter
│   └── backoffice/          # Next.js admin for owners
├── packages/
│   └── shared/              # types, zod schemas, calculateTotals()
└── docker-compose.yml       # mongo (replica set), redis

Things that bite you in production

A short list of lessons that you usually learn the hard way:

  • Clock drift. Terminal clocks are often wrong. Store both the terminal time (createdAt) and the server time (syncedAt), and use server time for anything legal like tax periods.
  • Receipt numbers offline. A central counter does not work offline. Give each terminal a prefix (S1-, S2-) and its own local sequence.
  • Price changes mid-sale. If the catalog syncs while a cart is open, keep the price that was on screen when the item was scanned. The customer saw that price.
  • Duplicate scans. Scanners sometimes double-read. A quantity of 2 that appears within 300 ms of the first scan is worth a gentle warning.
  • Backups and exports. Shop owners need their data for accountants. A daily CSV or JSON export of sales is a feature, not an afterthought.

What is next in this series

This post laid the foundation. In the next parts we will build each module end to end:

  1. Setting up the monorepo, MongoDB replica set and the shared package
  2. The catalog and back office product screens
  3. The checkout screen with barcode scanning and keyboard shortcuts
  4. Offline sync in depth, including conflict cases and testing it with a flaky network
  5. Payments, split payments and refunds
  6. Shifts, cash drawer and end-of-day reports
  7. Deploying the API and the PWA to production

If you want to follow along, the POS project page on Eskillsfy will track each module as it ships. And if you are building your own POS for a real shop, I would love to hear what your counter needs that I have not covered here.