> ## Documentation Index
> Fetch the complete documentation index at: https://docs.usetusk.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Next.js

> Learn how to initialize Tusk Drift in a Next.js application

## 1. Configure Next.js with `withTuskDrift`

Wrap your Next.js configuration with the `withTuskDrift` function in your `next.config.js` or `next.config.mjs` file:

### Basic Configuration

<Tabs>
  <Tab title="CommonJS (next.config.js)">
    ```javascript theme={null}
    const { withTuskDrift } = require("@use-tusk/drift-node-sdk/next");

    module.exports = withTuskDrift({
      // Your Next.js config
    });
    ```
  </Tab>

  <Tab title="ESM (next.config.mjs)">
    ```javascript theme={null}
    import { withTuskDrift } from "@use-tusk/drift-node-sdk/next";

    export default withTuskDrift({
      // Your Next.js config
    });
    ```
  </Tab>
</Tabs>

### With Debug Logging for Next.js Integration

<Tabs>
  <Tab title="CommonJS (next.config.js)">
    ```javascript theme={null}
    const { withTuskDrift } = require("@use-tusk/drift-node-sdk/next");

    module.exports = withTuskDrift(
      {
        // Your Next.js config
      },
      {
        // Tusk Drift options
        debug: true, // Enable debug logging
      },
    );
    ```
  </Tab>

  <Tab title="ESM (next.config.mjs)">
    ```javascript theme={null}
    import { withTuskDrift } from "@use-tusk/drift-node-sdk/next";

    export default withTuskDrift(
      {
        // Your Next.js config
      },
      {
        // Tusk Drift options
        debug: true, // Enable debug logging
      },
    );
    ```
  </Tab>
</Tabs>

### What `withTuskDrift` Does

The `withTuskDrift` wrapper automatically:

* Enables the Next.js instrumentation hook (for Next.js \< 15.0.0-rc.1)
* Configures webpack externals for proper module interception
* Detects your Next.js version and adjusts configuration accordingly
* Preserves your existing Next.js configuration

### Configuration Options

<table>
  <thead>
    <tr>
      <th>Option</th>
      <th>Type</th>
      <th>Default</th>
      <th>Description</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td><code>debug</code></td>
      <td><code>boolean</code></td>
      <td><code>false</code></td>
      <td>Enable debug logging to see what Tusk Drift is configuring during build.</td>
    </tr>

    <tr>
      <td><code>disableInstrumentationHook</code></td>
      <td><code>boolean</code></td>
      <td><code>false</code></td>
      <td>Disable automatic setting of <code>experimental.instrumentationHook</code>. Not recommended, will break Tusk Drift's Next.js integration.</td>
    </tr>

    <tr>
      <td><code>suppressWarnings</code></td>
      <td><code>boolean</code></td>
      <td><code>false</code></td>
      <td>Suppress all warnings from Tusk Drift's Next.js integration.</td>
    </tr>
  </tbody>
</table>

## 2. Create instrumentation file

Create an `instrumentation.ts` (or `.js`) file at the **root of your Next.js project** (or inside the `src` folder if using one):

```typescript theme={null}
// instrumentation.ts
export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    const { TuskDrift } = await import("@use-tusk/drift-node-sdk");

    TuskDrift.initialize({
      // Add API key once you are initializing Cloud
      // apiKey: process.env.TUSK_DRIFT_API_KEY,
      env: process.env.NODE_ENV,
      logLevel: "debug",
    });

    // Mark app as ready immediately
    TuskDrift.markAppAsReady();
  }
}
```

More context on setting up instrumentations for Next.js apps can be found [here](https://nextjs.org/docs/app/guides/instrumentation).

### Initialization Parameters

<table>
  <thead>
    <tr>
      <th>Option</th>
      <th>Type</th>
      <th>Default</th>
      <th>Description</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td><code>apiKey</code></td>
      <td><code>string</code></td>
      <td><b>Required if using Tusk Cloud</b></td>
      <td>Your Tusk Drift API key from the <a href="https://usetusk.ai/app/settings/api-keys">dashboard</a>.</td>
    </tr>

    <tr>
      <td><code>env</code></td>
      <td><code>string</code></td>
      <td><code>process.env.NODE\_ENV</code></td>
      <td>The environment name (e.g., 'dev', 'staging', 'production').</td>
    </tr>

    <tr>
      <td><code>logLevel</code></td>
      <td><code>'silent' | 'error' | 'warn' | 'info' | 'debug'</code></td>
      <td><code>'info'</code></td>
      <td>The logging level for the Tusk Drift SDK.</td>
    </tr>

    <tr>
      <td><code>samplingRate</code></td>
      <td><code>number</code></td>
      <td><code>1.0</code></td>
      <td>Override the base sampling rate (0.0 - 1.0) for recording. Takes precedence over <code>TUSK\_RECORDING\_SAMPLING\_RATE</code> and config file base-rate settings.</td>
    </tr>
  </tbody>
</table>

## 3. Update package.json scripts

In your `package.json` file, manually add a script for `"dev:record"` that allows you to start the service with Tusk Drift in record mode.

```json theme={null}
{
  "scripts": {
    "dev": "next dev",
    "dev:record": "TUSK_DRIFT_MODE=RECORD next dev"
  }
}
```

## 4. Update recording configurations

Update the `.tusk/config.yaml` file in your project root to include recording configurations.

If you're testing Tusk Drift out locally for the first time, use `fixed` mode
with a base rate of `1.0`. After testing, we generally recommend `adaptive`
mode with a base rate between `0.01` and `0.1`.

```yaml theme={null}
# ... existing configuration ...

recording:
  sampling:
    mode: adaptive
    base_rate: 0.1
    min_rate: 0.01
    log_transitions: true
  export_spans: true
  enable_env_var_recording: true
```

`TUSK_RECORDING_SAMPLING_RATE` overrides `recording.sampling.base_rate`.
`TUSK_SAMPLING_RATE` is still supported as a legacy alias, and
`recording.sampling_rate` remains a legacy config alias.

### Configuration Options

<table>
  <thead>
    <tr>
      <th>Option</th>
      <th>Type</th>
      <th>Default</th>
      <th>Description</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td><code>sampling.mode</code></td>
      <td><code>string</code></td>
      <td><code>"fixed"</code></td>
      <td>Selects constant sampling or adaptive load shedding.</td>
    </tr>

    <tr>
      <td><code>sampling.base\_rate</code></td>
      <td><code>number</code></td>
      <td><code>1.0</code></td>
      <td>The base sampling rate (0.0 - 1.0). In <code>fixed</code> mode this is the effective rate. In <code>adaptive</code> mode the SDK may temporarily reduce below this base rate.</td>
    </tr>

    <tr>
      <td><code>sampling.min\_rate</code></td>
      <td><code>number</code></td>
      <td><code>0.001</code> in <code>adaptive</code> mode</td>
      <td>The minimum steady-state sampling rate for adaptive mode. In critical conditions the SDK can still temporarily pause recording.</td>
    </tr>

    <tr>
      <td><code>sampling.log\_transitions</code></td>
      <td><code>boolean</code></td>
      <td><code>true</code></td>
      <td>Controls whether the SDK emits adaptive-sampling transition logs. Can also be overridden by <code>TUSK\_RECORDING\_SAMPLING\_LOG\_TRANSITIONS</code>.</td>
    </tr>

    <tr>
      <td><code>sampling\_rate</code></td>
      <td><code>number</code></td>
      <td><code>None</code></td>
      <td>Legacy alias for <code>recording.sampling.base\_rate</code>. Still supported for backward compatibility.</td>
    </tr>

    <tr>
      <td><code>export\_spans</code></td>
      <td><code>boolean</code></td>
      <td><code>false</code></td>
      <td>Whether to export spans to the Tusk backend. If false, spans are only saved locally in <code>.tusk/traces</code>.</td>
    </tr>

    <tr>
      <td><code>enable\_env\_var\_recording</code></td>
      <td><code>boolean</code></td>
      <td><code>false</code></td>
      <td>Whether to record and replay environment variables. Recommended for accurate replay behavior if your app's logic depends on environment variables.</td>
    </tr>
  </tbody>
</table>

To record your first set of API tests with Tusk Drift, view [this guide](/api-tests/record-replay-tests).

## Troubleshooting

<AccordionGroup>
  <Accordion title="My packages aren't being instrumented">
    If logs are showing that your packages aren't being instrumented:

    1. **Check file location**: Ensure `instrumentation.ts` is at the project root (same level as `next.config.js`), not in the `app` or `pages` directory.

    2. **Check runtime guard**: Make sure you have the `NEXT_RUNTIME === 'nodejs'` check in your `register()` function.

    3. **Enable debug logging**: Set `debug: true` in your `withTuskDrift` options to see what's being configured.
  </Accordion>
</AccordionGroup>
