NextJS recipe: Tracking 404s with Plausible and NextJS App Router

By default, all pages are statically rendered. If you add any backend or middleware logic to your NextJS page, it will be rendered as a server component.

Plausible Analytics requires access to the window object to track 404 events. So create a client component.

'use client';

import Script from "next/script";

export default function FourOhFourEvent() {
    return <Script onReady={() => window.plausible('404', { props: { path: window.location.pathname } })} />

Then create app/not-found.tsx:

import FourOhFourEvent from "./path/to/component/FourOhFourEvent";

export default function Page() {
    return (
            <FourOhFourEvent />
            <h1>Not Found</h1>