Quick answer
PostHog is an open source analytics tool that records what visitors do on your site: page views, completed orders, and any event you name. This post installs the Node SDK and tracks six real shop orders against a local server. It also shows the one mistake that loses every event: exiting before the SDK flushes its queue.
You ship a shop, orders come in, and someone asks what every shop owner asks: which pages do people visit before they buy, and where do they give up? Server logs show which pages were requested, but not that one visitor viewed three products, started a checkout, and then left. That gap is what event tracking fills: one named event per meaningful action, tied to the person who did it. PostHog is built for exactly that job, and it runs hosted or on your own server. This post installs the Node SDK, sends real events, and checks what arrived before you trust it with a live shop.
What I would check before using it
My first check is where the data lives. PostHog Cloud is the quick start: sign up, take a project API key, send events. Self-hosting keeps the data on your own machines, but upgrades, backups, and storage then become your job.
My second check is which events are worth naming. An event should answer a question you will actually decide on. "Order completed" with a city and a total answers one: where is the money coming from. A shop needs a short list: page viewed, product viewed, checkout started, order completed, payment failed.
My third check is identity. Every event carries a distinctId, the id of the person who did it. Anonymous visitors get an anonymous id until they sign in, and the two can be linked, but only if you plan for it. Decide before launch: one stable id per customer, never a shared id, never an email or phone number as the id.
My fourth check is volume and privacy together. Events are cheap to send and expensive to store, so check the free tier and agree a plan for growth: sample, drop noisy events, or pay. Never attach data you would not want in a log file: no passwords, no card details, no full addresses. The Grafana dashboard post shows the next step, a dashboard over events, and the OpenTelemetry tracing post covers tracing one request instead of counting visitors.
My verdict, as judgement: adopt PostHog for a small shop that needs to know what visitors do before buying. The recommendation flips if you only need page counts, because plain web analytics is simpler, or if nobody looks at the data weekly.
Six orders, seven events, and the ones that never arrived
The demo is a shop with six orders: Sana and Hamza in Karachi, Daniyal and Ayesha in Lahore, Mahnoor and Bilal in Islamabad. The script sends one page view and one "order completed" event per order, seven events in total, each with city and total in rupees. The totals come from the events that arrived, so a lost event means a wrong total.
The SDK needs Node 20 or later; this machine runs Node v24.22.1:
$ npm install posthog-node@~6.0
added 3 packages in 5s
That installs posthog-node 6.0.6. The demo points the SDK at a local capture server, so no account is needed. The server listens on port 8123, gunzips each request, logs the events, and replies in the shape the SDK expects. The reply must be {"results": {"": {"result": "ok"}}}, one result per event. Here is the server:
// Local stand-in for a PostHog host. Records every request the SDK sends,
// so the demo needs no PostHog account and no cloud call.
const http = require('node:http');
const zlib = require('node:zlib');
const fs = require('node:fs');
const LOG = 'captured-events.jsonl';
fs.writeFileSync(LOG, '');
const server = http.createServer((req, res) => {
const chunks = [];
req.on('data', (chunk) => { chunks.push(chunk); });
req.on('end', () => {
let raw = Buffer.concat(chunks);
if (req.headers['content-encoding'] === 'gzip') {
raw = zlib.gunzipSync(raw);
}
const results = {};
try {
const parsed = JSON.parse(raw.toString('utf8'));
const events = parsed.batch || [];
for (const event of events) {
fs.appendFileSync(LOG, JSON.stringify(event) + '\n');
results[event.uuid] = { result: 'ok' };
}
console.log(`capture server: received ${events.length} event(s) on ${req.url}`);
} catch (err) {
console.log(`capture server: ${req.url} (unparsable payload: ${err.message})`);
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ results }));
});
});
server.listen(8123, () => {
console.log('capture server listening on http://localhost:8123');
});
Here is the shop script. The REST API With Node.js and Express post shows the API these events would normally come from:
// Shop checkout events sent to PostHog (pointed at the local capture server).
const { PostHog } = require('posthog-node');
const orders = [
{ city: 'Karachi', customer: 'Sana', total: 12400 },
{ city: 'Lahore', customer: 'Daniyal', total: 9750 },
{ city: 'Islamabad', customer: 'Mahnoor', total: 15200 },
{ city: 'Karachi', customer: 'Hamza', total: 8300 },
{ city: 'Lahore', customer: 'Ayesha', total: 11850 },
{ city: 'Islamabad', customer: 'Bilal', total: 6400 },
];
async function main() {
const posthog = new PostHog('phc_local_demo_key', {
host: 'http://localhost:8123',
});
posthog.capture({
distinctId: 'visitor_001',
event: 'shop page viewed',
properties: { page: '/shop', city: 'Karachi' },
});
for (const order of orders) {
posthog.capture({
distinctId: order.customer.toLowerCase(),
event: 'order completed',
properties: { city: order.city, total: order.total },
});
}
console.log('Captured 7 events (1 page view, 6 orders).');
if (process.argv.includes('--shutdown')) {
await posthog.shutdown();
console.log('Shutdown complete: queued events flushed.');
} else {
console.log('Exiting without shutdown.');
}
}
main();
Now the run, and the thing that goes wrong. The script prints "Captured 7 events" either way, because capture() only queues events. Without a shutdown, nothing arrives:
$ node shop_events.js
Captured 7 events (1 page view, 6 orders).
Exiting without shutdown.
$ wc -l captured-events.jsonl
0
Zero events on the server: not one lost event, all seven. The fix is one line, await posthog.shutdown(), which flushes the queue before exit:
$ node shop_events.js --shutdown
Captured 7 events (1 page view, 6 orders).
Shutdown complete: queued events flushed.
$ wc -l captured-events.jsonl
7
Seven events arrived. A totals script reads that log and adds them up:
$ node totals.js
Orders by city (Rs):
Islamabad: Rs 21,600
Karachi: Rs 20,700
Lahore: Rs 21,600
Grand total: Rs 63,900 across 6 orders
The numbers check out by hand. The lesson is the gap between the runs: the script claimed seven events both times, and only the server log told the truth.
Common mistakes and how to fix them
First, exiting without shutdown. The symptom is a script that prints "Captured 7 events" while the server receives nothing. The fix is await posthog.shutdown() before exit.
Second, answering with the wrong shape from a local stand-in or proxy. The symptom is "[PostHog] 7 event(s) were not delivered to /i/v1/analytics/events: 7 failed with an unreadable response (HTTP 200)". The fix is to reply with {"results": {"": {"result": "ok"}}} for every event uuid, which is what posthog-node 6 expects.
Third, one distinctId for every visitor. The symptom is a funnel that looks like one person doing everything. The fix is one stable id per customer, set at sign-in.
Fourth, personal data in event properties. The symptom is card details, passwords, or full addresses sitting in the event log, readable by anyone with dashboard access. The fix is to send only what a decision needs, city and total here, and keep the rest out. The Sentry error tracking post shows the same rule from the error side.
Frequently Asked Questions
Is PostHog free?
Yes, for small use: open source code, a free tier on the cloud plan, and self-hosting where you pay for the machine instead.
Do I need a PostHog account to try the Node SDK?
Not for this demo, which points the SDK at a local server. For the real cloud you do, because the SDK needs your project API key.
What is the difference between PostHog Cloud and self-hosted?
Cloud is managed: PostHog runs the servers, storage, and upgrades. Self-hosted keeps the data on your machines, but the upgrades and backups become your job.
Does capture() send the event right away?
No. It queues the event and sends in batches, which is why the demo loses all seven events without shutdown. Call await posthog.shutdown() before exiting.
What to remember
- PostHog records named events with properties, tied to a person by distinctId.
- capture() only queues events; await posthog.shutdown() flushes them before exit.
- Without shutdown, this demo lost all 7 events.
- posthog-node 6 posts gzipped batches to /i/v1/analytics/events and expects a {"results": {...}} reply.
- Name events for decisions and keep personal data out of properties.
Where this leaves you
PostHog earns its place the first time a question about your shop gets a number instead of a guess. The demo showed the whole loop: a real install, seven events sent to a server you can inspect, six orders totalling Rs 63,900, and the one line that decides whether any of it arrives. That line, await posthog.shutdown(), is the difference between analytics and a script that only thinks it sent analytics. Install the SDK, point it at a local server, and watch the events land before you point it at real visitors.
Further reading
- PostHog Node.js SDK documentation
- PostHog documentation
- Grafana Dashboard Tutorial
- OpenTelemetry Python Tutorial: Trace a Checkout End to End
- Build Your First REST API With Node.js and Express
- Sentry Error Tracking With Python
Waqas Shahid is a software engineer from Karachi with more than 12 years of experience, including 6+ years in engineering leadership. He writes The Practical Developer.

Top comments (0)