Next.js Integration Guide
Integrate ZTLayer into your Next.js application for instant, edge-level protection against OWASP Top 10 vulnerabilities, credential stuffing, and volumetric layer 7 attacks.
The @ztlayer/nextjs SDK is built explicitly for the Next.js Edge Runtime and seamlessly integrates into the middleware.ts pipeline, ensuring threats are blocked before any React Server Components (RSC) or API routes are executed.
1. Installation
Install the official Next.js SDK via your preferred package manager.
npm install @ztlayer/nextjs
# or using yarn
yarn add @ztlayer/nextjs
# or using pnpm
pnpm add @ztlayer/nextjs2. Configuration & Initialization
Set your API key as a secure environment variable.
[!CAUTION] Never prefix this key with
NEXT_PUBLIC_or it will be bundled into your client-side JavaScript.
# .env.local
ZTLAYER_API_KEY="zt_live_xxxxxxxxxxxxxxxxxxxxxxxx"App Router Setup (Recommended)
Create or update the middleware.ts (or src/middleware.ts) file at the root of your project.
// src/middleware.ts
import { ZTLayerNext } from '@ztlayer/nextjs';
import { NextResponse } from 'next/server';
// 1. Initialize the security layer
export const middleware = ZTLayerNext({
apiKey: process.env.ZTLAYER_API_KEY,
// Optional: Define custom routing rules
routes: {
// Only inspect traffic hitting these paths
protect: ['/api/:path*', '/dashboard/:path*', '/login'],
// Explicitly bypass static assets for performance
exclude: ['/_next/static/:path*', '/images/:path*', '/favicon.ico']
},
// Optional: Pass through to another middleware after inspection
onPass: (req) => {
// You can chain other middlewares here (e.g., next-auth)
return NextResponse.next();
}
});
// 2. Configure the Next.js matcher to avoid invoking the Edge function unnecessarily
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
*/
'/((?!_next/static|_next/image|favicon.ico).*)',
],
};3. Vercel & Production Deployment
When deploying to Vercel, the ZTLayer middleware compiles natively to a Vercel Edge Function. This guarantees sub-millisecond execution times globally.
Production Checklist:
- Vercel Environment Variables: Add
ZTLAYER_API_KEYin your Vercel Project Settings > Environment Variables. - Edge Compatibility: The SDK uses standard Web APIs (
fetch,Request,Response). Ensure you do not import Node.js core modules (fs,crypto) insidemiddleware.ts. - Fail-Open Configuration: By default, ZTLayer
failModeis set to'open'. If the ZTLayer API experiences a catastrophic outage, your Next.js application will continue to function normally.
4. Advanced: Capturing Client Biometrics (Optional)
If you have enabled Strict Behavioral Analysis in the ZTLayer Dashboard to combat advanced credential stuffing bots, you must inject the client-side telemetry script.
Add the ZTProvider to your Root Layout:
// src/app/layout.tsx
import { ZTProvider } from '@ztlayer/react';
import './globals.css';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<ZTProvider projectId="your_public_project_id">
{children}
</ZTProvider>
</body>
</html>
);
}Note: The projectId is a public identifier, distinct from your secret API key.
5. Troubleshooting Common Next.js Errors
DynamicServerError: Dynamic server usage
- Cause: You are attempting to read cookies or headers dynamically inside a statically generated page after the middleware has fired.
- Fix: Ensure your React components properly handle dynamic data according to the Next.js App Router caching guidelines.
High Latency / Slow TTFB
- Cause: You did not configure the
config.matcherarray inmiddleware.ts. - Fix: The middleware is inspecting every single static asset (CSS, JS, Images). Copy the
config.matcherexample above to bypass static files.
Next Steps
- React Integrations: Learn more about the client-side telemetry SDK.
- API Reference: Automate ZTLayer configuration.
