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

Caleb FarukiCaleb Faruki
1 min read

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>
        </>
    )
}
0
Subscribe to my newsletter

Read articles from Caleb Faruki directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Caleb Faruki
Caleb Faruki