# 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.

Source: https://crustat.com/docs/getting-started/nextjs

## 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

```sh
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>`:

```tsx
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:

```tsx
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](https://crustat.com/docs/tracking/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](https://crustat.com/docs/account/sites-and-domains).

## Crawlers

AI and search bots mostly don't run scripts, so the component doesn't see them. One line in your middleware reports them, see [which AI and search bots read your site](https://crustat.com/docs/tracking/crawlers).

## 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](https://crustat.com/docs/getting-started/troubleshooting).
