Next.js SDK
Framework integration for Next.js apps with @vanta-dev/next.
The Next.js SDK wires Vanta into a Next.js app on both the server and the client. The server helpers give you a request-scoped client that does not leak state between requests, while client components use the browser SDK.
Installation
bash
npm install @vanta-dev/nextServer vs client
Next.js runs some code on the server and some in the browser. Vanta follows the same split.
- Server components, server actions, and route handlers track events server-side.
- Client components track events in the browser.
- Never put a server-only API key in client code.
Server-side tracking
Server action
Use the server helper inside a server action to record server-side events with the full server API key.
typescript
'use server'
import { track } from '@vanta-dev/next'
export async function checkout(cartId: string) {
await track({
event: 'checkout.started',
data: { cartId }
})
return { ok: true }
}Route handler
The same helper works in a route handler.
typescript
import { NextResponse } from 'next/server'
import { track } from '@vanta-dev/next'
export async function POST(request: Request) {
const body = await request.json()
await track({
event: 'api.upload',
data: {
size: body.size
}
})
return NextResponse.json({ received: true })
}Request-scoped client
Client-side tracking
Client components use the browser SDK through the same hooks as the React SDK. Mark the component with use client.
Client component
tsx
'use client'
import { useVanta } from '@vanta-dev/next'
export function ShareButton() {
const vanta = useVanta()
function handleShare() {
vanta.track({
event: 'link.shared',
data: { page: window.location.pathname }
})
}
return <button onClick={handleShare}>Share</button>
}Best practices
- Respect Server vs Client Components: track server events with the server helper and client events with browser helpers.
- Keep the server API key out of the client bundle entirely.
- Track side effects (checkouts, uploads, signups) on the server and pure interactions on the client.
- Keep client components that call hooks small and focused.