Next.js
This documentation is for version
1.x.x
If you are running with version
0.x.x
of the Next.js module, please follow this documentation.
This module intends to be used with the Next.js framework.
This documentation describes both server-side and client-side integrations.
Compatibility
- Next.js 13+
Prerequisites
- The server-side key available in your DataDome dashboard
- The client-side key available in your DataDome dashboard
Installation
The module can be installed as an npm package:
npm install @datadome/module-nextjs
Usage
Server-side configuration
The DataDome server-side part is built as a Next.js middleware. As described in the Next.js documentation, the following conditions need to be respected to create a middleware:
- The middleware needs to be defined in a
middleware.js
/middleware.ts
file - This file need to be located at the root of your project
- This file needs to either declare:
- a
export default
function - a exported function named
middleware
- a
import type { NextRequest } from 'next/server';
import { DataDomeMiddleware } from '@datadome/module-nextjs';
export const config = {
/**
* Match all request paths except for the ones starting with:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
*
* It avoids to send those requests to the DataDome's integration.
* @see {@link https://nextjs.org/docs/pages/building-your-application/optimizing/static-assets}
*/
matcher: ['/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)'],
};
const ddMiddleware = new DataDomeMiddleware('YOUR_SERVER_SIDE_KEY');
export default async function middleware(req: NextRequest) {
return ddMiddleware.handleRequest(req);
}
Client-side configuration
In order to enhance the detection, you need to install the JS Tag in your Next.js project by creating a custom App component.
It will load the JS Tag in the <head>
element so it can run as early as possible and intercept block responses on XHR and Fetch requests.
import type { AppProps } from "next/app";
import Script from "next/script";
import { DataDomeComponent } from "@datadome/module-nextjs";
function MyApp({ Component, pageProps }: AppProps) {
return (
<>
{/* DataDome bot protection */}
<DataDomeComponent clientSideKey={process.env.NEXT_PUBLIC_DATADOME_CLIENT_SIDE_KEY!} />
<Component {...pageProps} />
</>
);
}
export default MyApp;
Settings
Server-side settings
Setting | Description | Default |
---|---|---|
endpointHost | Host of the Protection API. | 'api.datadome.co' |
logger | The Logger instance to use in the module. | console |
timeout | The timeout limit for requests sent to the Protection API, in milliseconds | 150 |
urlPatternExclusion | Regex to match to exclude requests from being processed with the Protection API. | Extensions for static assets |
The
urlPatternInclusion
option does not exist on this module.To define an inclusion pattern, you can use the matcher from the configuration of your middleware file.
Here is an example of configuration with default values that you can modify according to your needs:
const ddMiddleware = new DataDomeMiddleware('YOUR_SERVER_SIDE_KEY', {
endpointHost: 'api.datadome.co',
logger: console,
timeout: 150,
urlPatternExclusion: /\.(avi|avif|bmp|css|eot|flac|flv|gif|gz|ico|jpeg|jpg|js|json|less|map|mka|mkv|mov|mp3|mp4|mpeg|mpg|ogg|ogm|opus|otf|png|svg|svgz|swf|ttf|wav|webm|webp|woff|woff2|xml|zip)$/i,
});
Client-side settings
Setting | Description | Default |
---|---|---|
clientSideKey | Your client-side key. | |
options | The options of the JS Tag. | {} |
tagsUrl | The source URL of the JS Tag. | https://js.datadome.co/tags.js |
Here is an example of configuration with default values that you can modify according to your needs:
<DataDomeComponent
clientSideKey={"YOUR_CLIENT_SIDE_KEY"}
options={{}}
tagsUrl={"https://js.datadome.co/tags.js"}
/>
FAQ
How to chain multiple middleware?
If you already have middleware in places, or you want to add several middleware with the DataDome's integration, you need to slightly change the server-side configuration in order chain the middlewares.
You need to:
- Define a
datadomeMiddleware
function that will call the Next.js module - Instantiate a
NextResponse
in themiddleware
function, and use it across your middlewares - Provide the response to the
handleRequest
DataDome's middleware method - Check the response status after the call of the
datadomeMiddleware
function and return the response in case of 403 status code
const ddMiddleware = new DataDomeMiddleware('YOUR_SERVER_SIDE_KEY');
async function datadomeMiddleware(req: NextRequest, res?: NextResponse) {
return ddMiddleware.handleRequest(req, res);
}
function firstMiddleware(req: NextRequest, res: NextResponse) {
res.headers.append('X-First-Header', 'Foo');
return res;
}
function thirdMiddleware(req: NextRequest, res: NextResponse) {
res.headers.append('X-Third-Header', 'Bar');
return res;
}
export default async function middleware(req: NextRequest) {
// Instantiate a NextResponse
let res = new NextResponse();
// Call first middleware
res = firstMiddleware(req, res);
// Call DataDome's Middleware
res = await datadomeMiddleware(req, res);
if (res.status === 403) {
return res;
}
// Third middleware will not be called if datadomeMiddleware returns a 403 status code
res = thirdMiddleware(req, res);
return res;
}
🚧 How to deploy on Vercel infrastructure? 🚧
Environment variables for the browser
The DataDome client-side key must be available in the browser, for this reason it must match the naming convention defined in the Nextjs documentation and be prefixed by
NEXT_PUBLIC_
.
DataDome provides an example that you can reuse to integrate the DataDome module inside your Vercel app.
- Access to the example repository
- Click on the "Deploy" button on the repository's README documentation
- Add a DATADOME_SERVER_SIDE_KEY variable inside Your Vercel Project > Project Settings > Environment Variables with the
server-side
key that you can find in the Management section of your dashboard - Also add a NEXT_PUBLIC_DATADOME_CLIENT_SIDE_KEY variable with the
client-side
key from your dashboard
- Update other settings if needed
- Redeploy your Vercel app
Updated 1 day ago