/ Back to Journal
Engineering

How I Replaced a Fake View Counter with Real Analytics on a Static Next.js Site

11/11/2026
7 Min Read
How I Replaced a Fake View Counter with Real Analytics on a Static Next.js Site

I had a number on my admin dashboard that said 1,250 views. It looked great, but it was fake.

It was a hard-coded placeholder I'd left in while building the dashboard, with a comment that said "still dummy until we implement view tracking." Every time I opened the admin panel, that number quietly lied to me. So I fixed it, without adding Google Analytics, a cookie banner, or a server.

This post walks through how I built first-party page view tracking for a statically exported Next.js site using Supabase, and the security decisions that make it safe to do entirely from the browser.

The constraint: there is no server

My portfolio is a Next.js app built with output: 'export' and hosted on Firebase Hosting. That means:

  • No API routes
  • No getServerSideProps
  • No middleware running on each request

Every page is just HTML, CSS and JavaScript sitting on a CDN. If I want to record a visit, the visitor's browser has to do it.

That rules out the usual "log the request on the server" approach and raises an obvious question: if the browser writes directly to my database, what stops anyone from reading or tampering with that data?

The answer is Row Level Security.

Why not just use Google Analytics?

I considered it. But for a personal portfolio, I wanted something that:

  1. Lives in my own database, next to the rest of my content, so the admin dashboard can query it directly.
  2. Doesn't need a cookie banner. I'm not setting tracking cookies or building visitor profiles.
  3. Has zero extra dependencies. I already ship the Supabase client. Adding another third-party script would only make the site heavier.
  4. Is something I understand end to end. If the number is wrong, I know exactly where to look.

Third-party analytics tools are excellent at what they do. I just didn't need most of what they do.

Step 1: The table

The schema is deliberately small:

CREATE TABLE IF NOT EXISTS public.page_views (
    id BIGSERIAL PRIMARY KEY,
    path TEXT NOT NULL,
    referrer TEXT,
    session_id TEXT,
    user_agent TEXT,
    created_at TIMESTAMP WITH TIME ZONE
        DEFAULT timezone('utc'::text, now()) NOT NULL
);

CREATE INDEX IF NOT EXISTS page_views_created_at_idx
    ON public.page_views (created_at);
CREATE INDEX IF NOT EXISTS page_views_path_idx
    ON public.page_views (path);

Each row is one view. I store the path, where the visitor came from, a random per-tab session ID, and the user agent. No IP addresses, no names, no fingerprinting.

The two indexes are there for the queries I know I'll want next: "views in the last 7 days" (created_at) and "most visited pages" (path).

Step 2: Row Level Security does the heavy lifting

This is the part that matters most.

The Supabase "anon" key ships in my JavaScript bundle. Anyone can open DevTools and copy it. That's by design. The anon key isn't a secret, and Supabase expects it to be public. What protects the data is the RLS policies on each table.

For page views, I want two rules:

  • Anyone can add a view.
  • Only me, signed in to the admin panel, can read views.
ALTER TABLE public.page_views ENABLE ROW LEVEL SECURITY;

-- Anyone (anonymous visitors) can record a view
CREATE POLICY "Allow public insert" ON public.page_views
    FOR INSERT TO anon, authenticated
    WITH CHECK (true);

-- Only the authenticated admin can read view data
CREATE POLICY "Enable read access for authenticated users only"
    ON public.page_views
    FOR SELECT TO authenticated
    USING (auth.uid() IS NOT NULL);

Notice what's missing: there are no UPDATE or DELETE policies. With RLS enabled, anything not explicitly allowed is denied. So even with the public key, a visitor can't:

  • read other people's visits,
  • edit existing rows, or
  • wipe the table.

They can only append. That's the whole security model, and it's about ten lines of SQL.

Step 3: The tracker

On the client, I wrote a small trackPageView function. It has three jobs: normalise the path, skip views I don't want to count, and insert the row.

export async function trackPageView(rawPath: string): Promise<void> {
  if (typeof window === 'undefined') return;

  const path = (rawPath.split(/[?#]/)[0] || '/').replace(/(.)\/$/, '$1');
  if (path.startsWith('/admin')) return;
  if (!markSeen(path)) return;

  try {
    const { error } = await supabase.from('page_views').insert({
      path,
      referrer: document.referrer || null,
      session_id: getSessionId(),
      user_agent: navigator.userAgent.slice(0, 500),
    });
    if (error) console.warn('Page view tracking failed:', error.message);
  } catch (error) {
    console.warn('Page view tracking failed:', error);
  }
}

A few details worth calling out:

Path normalisation. My site uses trailingSlash: true, so /blog/ and /blog would otherwise be counted as two different pages. Query strings and hash fragments are stripped too, so /projects?filter=mobile counts as /projects.

Admin pages are excluded. I open the dashboard constantly. Counting my own admin sessions would make the number meaningless.

Refreshes don't inflate the count. markSeen keeps a list of paths already recorded in sessionStorage. Refresh a page ten times and it counts once. Open it in a new tab later and it counts again. That's a reasonable middle ground between "every request" and "unique visitors".

Failure is silent. Tracking should never break the site. If Supabase is down, or an ad blocker blocks the request, the visitor never notices. The function warns in the console and moves on.

It never reads anything back. supabase-js v2 doesn't return inserted rows unless you ask for them with .select(). That matters here, because the anon role isn't allowed to select from this table. Asking for the row back would make the insert fail.

Step 4: Hooking into the router

In a Next.js Pages Router app, client-side navigation doesn't reload the page, so tracking on first load alone would miss most visits. I listen for route changes in _app.tsx:

useEffect(() => {
  if (!router.isReady) return;
  trackPageView(router.asPath);

  const handleRouteChange = (url: string) => trackPageView(url);
  router.events.on('routeChangeComplete', handleRouteChange);
  return () => router.events.off('routeChangeComplete', handleRouteChange);
}, [router.isReady]);

Waiting for router.isReady matters on a static export. For dynamic routes like /blog/[slug], the real path isn't available until the router has hydrated. Without that check, the first view would be recorded as the literal string /blog/[slug].

Step 5: Showing the real number

The dashboard query is the easy part. Supabase can return a count without sending any rows over the network:

supabase.from('page_views').select('*', { count: 'exact', head: true })

head: true means "just give me the count". Because I'm signed in when this runs, the authenticated SELECT policy lets it through. If a logged-out visitor tried the same query, they'd get nothing.

The placeholder 1250 is gone, and the dashboard finally tells the truth.

The trade-offs, honestly

This is a deliberately simple system, and it has limits I chose to accept:

  • Bots get counted. I'm not filtering crawlers yet. The user_agent column means I can filter them later in a query without changing how data is collected.
  • Ad blockers can block it. Some privacy extensions block requests to known backend domains. My numbers are a floor, not an exact figure.
  • Anyone can spam inserts. The public insert policy means someone determined could write a script to add fake views. For a portfolio, the risk is low and the damage is one inflated number. If it ever became a problem, I'd move the insert into a Supabase Edge Function with rate limiting, or a Postgres function that validates input.
  • It's views, not unique visitors. The session ID is per tab and isn't persisted, so I can't (and don't want to) follow someone across visits.

Knowing where a system falls short is as important as building it. Every item on this list has a clear upgrade path if I ever need it.

What I took away from this

The interesting part of this feature wasn't the code. It was the security model. Once I accepted that the browser talks straight to the database and the key is public, the question changed from "how do I hide this?" to "what exactly is each role allowed to do?" Row Level Security answers that question in the database itself, where it can't be bypassed by anyone editing the JavaScript.

That shift, from trusting the client to defining permissions in the data layer, applies to almost every app built on Supabase or Firebase. Page view tracking just happened to be a small, low-stakes place to get it right.

Found this useful? Share it

Written By

Ephraim Umunnakwe

Architectural Software Engineer

Journal Archive

HAVE A VISION?

Let's discuss how we can build your next high-performance solution.

Start Conversation