Next.js Integration
Add AI Search Index to your Next.js application with the built-in Script component.
App Router (Next.js 13+)
Add the script to your root layout file:
app/layout.tsx
import Script from 'next/script'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>
{children}
<Script
src="https://www.aisearchindex.com/pixel.js"
data-tid="YOUR_TRACKING_ID"
data-spa="true"
strategy="afterInteractive"
/>
<noscript><img src="https://www.aisearchindex.com/api/pixel?tid=YOUR_TRACKING_ID" width="1" height="1" style="position:absolute;left:-9999px;visibility:hidden" alt="" /></noscript>
</body>
</html>
)
}Pages Router
Add the script to your _app.tsx file:
pages/_app.tsx
import Script from 'next/script'
import type { AppProps } from 'next/app'
export default function App({ Component, pageProps }: AppProps) {
return (
<>
<Component {...pageProps} />
<Script
src="https://www.aisearchindex.com/pixel.js"
data-tid="YOUR_TRACKING_ID"
data-spa="true"
strategy="afterInteractive"
/>
<noscript><img src="https://www.aisearchindex.com/api/pixel?tid=YOUR_TRACKING_ID" width="1" height="1" style="position:absolute;left:-9999px;visibility:hidden" alt="" /></noscript>
</>
)
}Script Loading Strategies
Next.js offers different loading strategies for scripts:
| Strategy | Description |
|---|---|
| afterInteractive | Recommended. Loads after the page is interactive. |
| lazyOnload | Loads during browser idle time. Good for non-critical scripts. |
| beforeInteractive | Loads before hydration. Not recommended for analytics. |
SPA Mode
Next.js uses client-side navigation, so make sure to enable SPA mode to track page transitions:
<Script
src="https://www.aisearchindex.com/pixel.js"
data-tid="YOUR_TRACKING_ID"
data-spa="true" // Important for Next.js!
strategy="afterInteractive"
/>Why SPA mode? Without it, only the initial page load is tracked. SPA mode listens for route changes and tracks each navigation.
TypeScript Note
If you see TypeScript errors about the data attributes, you can add them to your next-env.d.ts or create a declaration file:
types/script.d.ts
declare module 'next/script' {
interface ScriptProps {
'data-tid'?: string
'data-spa'?: string
'data-debug'?: string
'data-dnt'?: string
}
}Need more configuration?
Learn about all available options like debug mode and DNT support.
View Configuration Options