A real-time visitor badge is one of the smallest UI elements on a developer portfolio, yet it touches almost every layer of modern web engineering: serverless state, HTTP caching semantics, atomic concurrency, and non-blocking client hydration.
Most tutorials stop at “read a key, add one, write it back.” In production, that breaks almost immediately. Here is how I engineered the counter running on this site using the 2026 stack:
- Next.js 16.1 (App Router + Turbopack) — Async
cookies()API and explicit dynamic route opt-outs. - React 19 — Clean
AbortControllereffect cleanup to prevent double-fetch race conditions under Strict Mode. - Upstash Redis (@upstash/redis v1.38+) — Stateless HTTP/REST Redis so serverless functions never exhaust TCP connection pools.
- Framer Motion 12 + Tailwind CSS v4 — Smooth layout-shift-free entrance with
tabular-nums.
1. Why Naive Counters Fail in Production
Lost Updates (Read-Modify-Write Race): If two visitors hit your route at the exact same millisecond and your code runs get() followed by set(count + 1), both read 500 and both write 501. Using Redis INCR executes atomically on Redis's single-threaded command loop.
Stale Edge / CDN Caching: Without export const dynamic = "force-dynamic" and Cache-Control: no-store, intermediate proxies or browser caches can serve a frozen count for hours.
Strict Mode Double Invocation: In development, React 19 mounts, unmounts, and remounts components. Without an AbortController, two concurrent requests fire before the first Set-Cookie header lands.
2. Environment & Dependencies
Provision a serverless Redis database in the Upstash Console, then install the REST client and animation library:
npm install @upstash/redis framer-motionUPSTASH_REDIS_REST_URL="https://your-endpoint.upstash.io"
UPSTASH_REDIS_REST_TOKEN="your-rest-token"3. Atomic Route Handler (Next.js 16)
In Next.js 16, cookies() is asynchronous. We check whether the visitor cookie is present: returning visitors only read the current value, while new sessions trigger an atomic redis.incr() and receive an httpOnly cookie valid for 1 year.
import { Redis } from "@upstash/redis";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
// Force dynamic evaluation so Next.js 16 never caches the GET response
export const dynamic = "force-dynamic";
const redis = new Redis({
url: process.env.KV_REST_API_URL || process.env.UPSTASH_REDIS_REST_URL || "",
token: process.env.KV_REST_API_TOKEN || process.env.UPSTASH_REDIS_REST_TOKEN || "",
});
const VISITOR_KEY = "portfolio:visitors";
const COOKIE_NAME = "visitor";
export async function GET() {
try {
const cookieStore = await cookies();
const hasVisited = cookieStore.has(COOKIE_NAME);
let count = await redis.get<number>(VISITOR_KEY);
if (count === null) {
// Seed initial count atomically if the key does not exist yet
count = 1;
await redis.set(VISITOR_KEY, count);
} else if (!hasVisited) {
// Single-threaded atomic increment — safe under concurrent traffic
count = await redis.incr(VISITOR_KEY);
}
const response = NextResponse.json(
{ count },
{
headers: {
"Cache-Control": "no-store, no-cache, must-revalidate",
},
}
);
if (!hasVisited) {
response.cookies.set(COOKIE_NAME, "1", {
maxAge: 60 * 60 * 24 * 365,
path: "/",
httpOnly: true,
sameSite: "lax",
secure: process.env.NODE_ENV === "production",
});
}
return response;
} catch (error) {
console.error("[Visitor API] Redis error:", error);
return NextResponse.json({ count: null }, { status: 500 });
}
}4. Zero-Jitter Client Component
On the client, we fetch with cache: "no-store", cancel in-flight requests on unmount via AbortController, and use tabular-nums so digits align cleanly across theme modes.
"use client";
import { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
export default function VisitorCounter() {
const [count, setCount] = useState<number | null>(null);
useEffect(() => {
const controller = new AbortController();
fetch("/api/visitor", {
signal: controller.signal,
cache: "no-store",
})
.then((res) => (res.ok ? res.json() : Promise.reject(res.status)))
.then((data) => {
if (typeof data?.count === "number") {
setCount(data.count);
}
})
.catch((err) => {
if (err?.name !== "AbortError") {
console.error("Failed to fetch visitor count:", err);
}
});
return () => controller.abort();
}, []);
return (
<AnimatePresence mode="wait">
{count !== null && (
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -8 }}
transition={{ duration: 0.45, ease: [0.23, 1, 0.32, 1] }}
className="flex w-fit items-center gap-2 rounded-full border border-neutral-200 bg-neutral-100/60 px-3 py-1.5 backdrop-blur-sm dark:border-neutral-800 dark:bg-neutral-900/60"
>
<span className="relative flex h-2 w-2">
<span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-75" />
<span className="relative inline-flex h-2 w-2 rounded-full bg-emerald-500" />
</span>
<p className="text-xs font-semibold tracking-tight text-neutral-600 dark:text-neutral-400">
<span className="tabular-nums text-neutral-900 dark:text-neutral-100">
{count.toLocaleString()}
</span>
<span className="ml-1.5 opacity-75">unique visitors</span>
</p>
</motion.div>
)}
</AnimatePresence>
);
}5. Scaling Beyond Cookies: HyperLogLog
HTTP-only cookies are lightweight and zero-friction for portfolios, though users in incognito mode or clearing storage will be counted again. If you ever need strict deduplication at high traffic without storing millions of IP strings, Redis HyperLogLog estimates unique cardinality in constant 12 KB of memory with ~0.81% standard error:
// Optional: Privacy-preserving cardinality at scale using HyperLogLog (~12 KB max)
import crypto from "crypto";
const fingerprint = crypto
.createHash("sha256")
.update(`${ip}:${userAgent}:${dailySalt}`)
.digest("hex");
await redis.pfadd("portfolio:visitors:hll", fingerprint);
const approxUniqueCount = await redis.pfcount("portfolio:visitors:hll");Takeaways
- Always use atomic Redis operations (
INCR/PFADD) instead of read-modify-write. - Explicitly opt out of static and CDN caching with
force-dynamicandno-store. - Keep UI transitions subtle and theme-aware so the widget feels native in both light and dark modes.