Skip to content

Add Crustat to a Next.js site

Install the @crustat/next package and render one component in your root layout. Works with the App Router and the Pages Router.

Before you start

You need a Next.js project on Next.js 13 or newer, with React 18 or newer, and your Crustat site ID. In Crustat, open your site, go to Site settings → Install and click Copy ID next to Site ID.

Install the package

npm install @crustat/next

pnpm add @crustat/next or yarn add @crustat/next work too.

App Router

Open your root layout, app/layout.tsx (or .jsx), and render the component once inside <body>:

import Crustat from '@crustat/next';

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Crustat siteId="YOUR-SITE-ID" />
      </body>
    </html>
  );
}

Unlike a hand-pasted line, this one goes in <body>. Next.js loads the script itself once the page is ready, so its spot in the layout doesn’t matter.

Pages Router

Open pages/_app.tsx (or .jsx) and render the component next to your page:

import type { AppProps } from 'next/app';
import Crustat from '@crustat/next';

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Component {...pageProps} />
      <Crustat siteId="YOUR-SITE-ID" />
    </>
  );
}

Render it once, in one of these two places, not on each page.

What it does

The component loads Crustat’s script through Next.js’s own script loader, once the page is ready. It’s the same script, with the same data-site ID, as the line you’d paste by hand. Next.js keeps it loaded as people move around your site.

Page changes

When someone clicks a link in a Next.js app, the page changes without a full reload. Crustat follows these changes on its own and records each one as a page view. See single-page apps for the details.

Testing

Visits from localhost are skipped on purpose, so next dev won’t show up in your stats. Deploy, then visit a page on your live site and wait about a minute.

Preview deployments on another address are recorded but left out of your stats, unless you add that address to the site. See add and manage your sites.

Optional: a Content-Security-Policy

If you set a Content-Security-Policy, for example in middleware or next.config.js, allow https://stats.crustat.com in script-src and connect-src.

Not seeing your visit? See visits aren’t showing up.

Still stuck? Write to hello@crustat.com.

All articles
The mascot waiting

Almost ready

We're opening to everyone soon.

Crustat is in its final checks before we open sign-ups. Leave your email and we'll write once, the day it opens, with your 14 days free waiting.

One email when we open. No newsletter. See our privacy page.