📘

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

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

SettingDescriptionDefault
endpointHostHost of the Protection API.'api.datadome.co'
loggerThe Logger instance to use in the module.console
timeoutThe timeout limit for requests sent to the Protection API, in milliseconds150
urlPatternExclusionRegex 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

SettingDescriptionDefault
clientSideKeyYour client-side key.
optionsThe options of the JS Tag.{}
tagsUrlThe 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:

  1. Define a datadomeMiddleware function that will call the Next.js module
  2. Instantiate a NextResponse in the middleware function, and use it across your middlewares
  3. Provide the response to the handleRequest DataDome's middleware method
  4. 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.

  1. Access to the example repository
  2. Click on the "Deploy" button on the repository's README documentation
  3. 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
  4. Also add a NEXT_PUBLIC_DATADOME_CLIENT_SIDE_KEY variable with the client-side key from your dashboard

  1. Update other settings if needed
  2. Redeploy your Vercel app