---
id: I0035
title: "Next.js live mint counter"
url: https://carbium.sh/library/integrate/next-js-live-mint-counter
collection: Integrations
category: Web frameworks
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Next.js live mint counter

A small Node service reads a Candy Machine account from Carbium every few seconds and pushes the items remaining to every open browser tab as server-sent events, so your Next.js mint page counts down after each mint without a visitor reloading.

## What the counter does

A mint page shows one number, the items left. It goes stale the moment someone else mints, because the page read it once when it loaded. This service keeps one fresh copy of that number on the server and pushes every change to all open tabs.

It is one Node process with `@solana/kit` as its only dependency. It finds the Candy Machine account, reads it every 3 seconds and serves the latest count at `GET /remaining` as server-sent events. A browser opens that URL with `new EventSource(url)` and receives a JSON message on connect and another each time the count changes. Each message carries `available`, `redeemed`, `remaining` and a UTC timestamp.

The poll is shared. Fifty tabs or five thousand add no calls to Carbium, because the tabs listen to the process and only the process reads the chain. That also keeps your RPC key on the server, out of the page and out of the browser's network log.

## Where the number lives

A Candy Machine v3 account is owned by the program `CndyV3LdqHUfDLmE5naZjVN8rBZz4tqhdefbAnjHG3JR`. Its first bytes are fixed-size fields, so the two numbers you need sit at known offsets and need no Anchor or Umi decoder.

| Bytes | Field | Type |
|---|---|---|
| 0 to 8 | account discriminator | 8 bytes |
| 8 to 16 | version, token standard, flag bits | 8 bytes |
| 16 to 112 | authority, mint authority, collection mint | 3 public keys |
| 112 to 120 | items redeemed | u64, little endian |
| 120 to 128 | items available | u64, little endian |

Umi's `fetchCandyMachine` returns the same two values as `candyMachine.itemsRedeemed` and `candyMachine.data.itemsAvailable`. Keep Umi for building the mint transaction in your app. The display reads from this service, so the number your visitors see needs no RPC call from their browsers.

> The offsets are for Candy Machine v3 on Token Metadata. The Core Candy Machine has its own layout and a different program, and the service refuses an account that the v3 program does not own.

## The service

Install with `npm install @solana/kit@8.6.0` and set `"type": "module"` in `package.json`. Node 24 strips the types on load. `CARBIUM_KEY` is required and the file exits with a message when it is missing. `CARBIUM_RPC_URL`, `POLL_MS` (default 3000), `PORT` (default 3001) and `ALLOW_ORIGIN` are optional. Pass the Candy Machine address as the first argument.

With no argument the service looks for a machine itself. It takes the 5 newest signatures of the Candy Machine program, reads each transaction, and tests the accounts in it for the first one the program owns that decodes to a sane count. A transaction call carries `maxSupportedTransactionVersion: 1`, since mainnet carries v1 transactions and a [call without it](https://carbium.sh/docs#rpc) answers -32015 for one. The account read is `getAccountInfo` at `confirmed`, set in the call.

`main.ts` (run: `node main.ts`)

```ts
// I0035 · Next.js live mint counter
// https://carbium.sh/library/integrate/next-js-live-mint-counter
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { createDefaultRpcTransport, createSolanaRpcFromTransport, address, type Address } from "@solana/kit";
import { createServer, type ServerResponse } from "node:http";

const key = process.env.CARBIUM_KEY;
if (!key) { console.error("Set CARBIUM_KEY."); process.exit(1); }
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);
const PROGRAM = address("CndyV3LdqHUfDLmE5naZjVN8rBZz4tqhdefbAnjHG3JR"); // Candy Machine v3
const POLL_MS = Math.max(1000, Number(process.env.POLL_MS) || 3000);
const PORT = Number(process.env.PORT) || 3001;
const timeout = () => AbortSignal.timeout(5_000);
const opts = { encoding: "base64", commitment: "confirmed" } as const;
const why = (e: unknown) => (e instanceof Error ? e.message : String(e));

type Count = { available: number; redeemed: number; remaining: number; at: string };
function decode(base64: string): Count | null {
  const data = Buffer.from(base64, "base64");
  if (data.length < 128) return null;
  const redeemed = Number(data.readBigUInt64LE(112));
  const available = Number(data.readBigUInt64LE(120));
  if (available === 0 || redeemed > available) return null; // not a v3 layout
  return { available, redeemed, remaining: available - redeemed, at: new Date().toISOString() };
}

async function read(machine: Address): Promise<Count | null> {
  const { value } = await rpc.getAccountInfo(machine, opts).send({ abortSignal: timeout() });
  return value && value.owner === PROGRAM ? decode(value.data[0]) : null;
}

type Tx = { transaction: { message?: { accountKeys?: Address[] } }; meta?: { loadedAddresses?: { writable: Address[]; readonly: Address[] } } | null };
async function find(): Promise<Address | null> {
  const sigs = await rpc.getSignaturesForAddress(PROGRAM, { limit: 5 }).send({ abortSignal: timeout() });
  for (const s of sigs) {
    try {
      const tx = (await rpc
        .getTransaction(s.signature, { commitment: "confirmed", encoding: "json", maxSupportedTransactionVersion: 1 })
        .send({ abortSignal: timeout() })) as unknown as Tx | null;
      if (!tx) continue; // an older signature can answer null
      const l = tx.meta?.loadedAddresses;
      const keys = [...new Set([...(tx.transaction.message?.accountKeys ?? []), ...(l?.writable ?? []), ...(l?.readonly ?? [])])].slice(0, 100);
      const { value } = await rpc.getMultipleAccounts(keys, opts).send({ abortSignal: timeout() });
      const i = value.findIndex((a) => a?.owner === PROGRAM && decode(a.data[0]) !== null);
      if (i >= 0) return keys[i];
    } catch (e) {
      console.error(`lookup of ${s.signature} failed:`, why(e));
    }
  }
  return null;
}

const clients = new Set<ServerResponse>();
let latest: Count | null = null;
const send = (res: ServerResponse) => res.write(`data: ${JSON.stringify(latest)}\n\n`);
createServer((req, res) => {
  if (req.url !== "/remaining") { res.writeHead(404).end(); return; }
  res.writeHead(200, {
    "content-type": "text/event-stream",
    "cache-control": "no-cache",
    "x-accel-buffering": "no",
    "access-control-allow-origin": process.env.ALLOW_ORIGIN ?? "*",
  });
  if (latest) send(res);
  clients.add(res);
  req.on("close", () => clients.delete(res));
}).listen(PORT);

const machine = process.argv[2] ? address(process.argv[2]) : await find().catch((e: unknown) => { console.error("lookup failed:", why(e)); return null; });
if (!machine) { console.error("No candy machine found in the newest transactions; pass its address."); process.exit(1); }
console.log(`watching ${machine}, stream on :${PORT}/remaining`);
for (;;) {
  try {
    const next = await read(machine);
    if (!next) console.error("not a readable Candy Machine v3 account");
    else if (next.redeemed !== latest?.redeemed || next.available !== latest?.available) {
      latest = next;
      console.log(`${next.remaining} of ${next.available} left (${next.redeemed} minted)`);
      for (const c of clients) send(c);
    }
  } catch (e) {
    console.error("poll failed:", why(e));
  }
  for (const c of clients) c.write(": ping\n\n");
  await new Promise((r) => setTimeout(r, POLL_MS));
}
```

## The Next.js side

In a client component, open the stream in an effect and close it on cleanup: `useEffect(() => { const es = new EventSource(url); es.onmessage = (e) => setCount(JSON.parse(e.data)); return () => es.close(); }, [])`. Render `count.remaining` and `count.available` from the state. The browser reconnects an EventSource after a drop on its own, and the service sends the current count first on every connection, so a reconnect catches up at once.

Run the service as a long-lived process beside the app, for example under systemd, and put it behind the same reverse proxy so the page and the stream share an origin and an https scheme. A page on https cannot open an http stream. Set `ALLOW_ORIGIN` to your site's origin when the stream lives on another host. To keep one origin inside Next, a route handler can return a `ReadableStream` with content type `text/event-stream` and call the same read function, but a serverless function ends its connections at its time limit, so a process that stays up is the safer home.

For the visitor who just minted, subtract one from the displayed count as soon as your own mint transaction lands, and let the next stream message overwrite it. The chain value arrives within one poll and corrects any drift.

## What it costs against your limits

`getAccountInfo` is an [account read](https://carbium.sh/docs#rpc) at 10 cells, and the rate for that class is 0.5, 15, 50 and 400 req/s on Free, Dev, Business and Pro. A poll every 3 seconds is 0.33 req/s and 200 cells a minute, inside Free's 0.5. A poll every 2 seconds sits exactly on the Free rate, so `POLL_MS` should stay at 2000 or above there. Dev allows a poll every 100 ms in principle, but a slot lasts about 200 ms, so a poll faster than that returns the same number.

[Limits are per account](https://carbium.sh/docs#limits), so every key you hold shares the budget with this service. A call that gets a 429 is logged and the next poll tries again, and visitors keep seeing the last count in the meantime.

The lookup that runs when you pass no address costs more: one `getSignaturesForAddress` at 50 cells, up to 5 `getTransaction` calls at 50 cells each, and a `getMultipleAccounts` at 10 cells per pubkey, capped at 100 pubkeys a call because the 1024-cell burst limits a call to 100 below Pro. It stops at the first transaction that holds a machine. In production pass the address and skip it.

## Where it ends

- It reads Candy Machine v3 on Token Metadata only. A Core Candy Machine, or any other account, is refused or decoded as an implausible count and dropped.
- The number is a display. Two visitors can both see 1 left and click, and the second mint fails on chain; the chain decides who gets the item.
- The count is as old as the poll interval plus the time a mint takes to confirm. A mint that never lands never shows.
- It shows the item count only. Start dates, per-wallet limits and phase prices live in the Candy Guard account, which this service does not read.
- The automatic lookup returns some Candy Machine found in recent transactions, which can be sold out or abandoned. It is there for a first run, and your own address replaces it.
- State sits in one process. Run one instance per machine address, or give each its own poll. A restart loses nothing, since the first poll reads the chain again.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The log shows `not a readable Candy Machine v3 account` and the page never updates. | The address is not the Candy Machine account itself. The collection mint, the Candy Guard address and a Core Candy Machine all fail here. Copy the Candy Machine address from your deploy output and pass it as the first argument. |
| The browser console shows an EventSource error and the counter stays empty. | Either the page is on https and the stream is on http, or the origin is not allowed. Serve both over https from one origin, or set `ALLOW_ORIGIN` to the page's origin. |
| The service runs but the number only changes in bursts, a minute apart. | A proxy in front is buffering the stream. The service sends `x-accel-buffering: no`, which nginx honours. For another proxy, turn off response buffering for `/remaining`. |
| The log shows `poll failed:` followed by an HTTP error status and the counter freezes. | A 401 means the key is wrong or cut short: `CARBIUM_KEY` holds the whole key. A 429 means the account's account-read budget is spent, usually by other keys on the account: raise `POLL_MS` or move to a plan with a [higher rate](https://carbium.sh/docs#limits). |
| The log shows `No candy machine found in the newest transactions`, or `lookup of ... failed`. | The newest program signatures held no machine you can read, or an older signature answered null from `getTransaction` because the address index reaches below the validator's ledger. Run again, or pass the machine address. |
| The stream drops every few minutes in production. | The process runs as a serverless function or behind a proxy with a short idle timeout. Run it as a normal long-lived process, and keep the 3 second poll, which also sends a keepalive comment line to every client. |

## Questions

### Why not call fetchCandyMachine from the browser every few seconds?

Each tab would make its own reads, so cost grows with visitors, and the RPC key would have to reach the page. One shared poll costs the same for one visitor or ten thousand.

### Can a WebSocket subscription replace the polling?

Possibly. Carbium's [accountSubscribe](https://carbium.sh/docs#websocket) sends account state on change for streamed accounts, so check that your machine notifies before you drop the poll. A subscription costs 5, 25 or 200 credits to open by filter weight, then 20 credits per MiB sent.

### What does it use on the Free plan?

One 10 cell account read every 3 seconds, so 200 cells a minute at 0.33 req/s against Free's 0.5 req/s for account reads.

### Does the same code work for a Core Candy Machine?

No. The Core version has a different program and layout, so the offsets in the table do not apply. The service checks the owner and refuses it.

## Related

- [NFT collection transfer feed](https://carbium.sh/library/blockchainideas/nft-collection-transfer-feed) (Blockchain ideas, BI0004)
- [Solana commitment levels](https://carbium.sh/library/howsolana/solana-commitment-levels) (How to use Solana, HS0003)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
