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

# React Router

> Script loading for React Router applications with data and framework modes

A React Router component for server-side script loading and rendering designed for React Router's **data mode** and **framework mode**. This package provides secure, cached script loading with TypeScript support for server-side rendering.

## React Router Modes

This package is designed specifically for:

* **Data Mode**: Using `createBrowserRouter` with loaders
* **Framework Mode**: Using React Router with Vite plugin and SSR

<Warning>
  This package is for **server-side rendering only**. The script loader will
  throw an error if it runs in the browser, and it is not suitable for pure
  client-side applications.
</Warning>

## Installation

```bash theme={null}
npm install @adunblock/server-tag-react-router
```

<Warning>
  Every rendered `<script>` tag **must** include a `data-code` attribute set
  to your Account ID (verification code). AdUnblock uses this value to verify
  that the script is running on your registered domain. Find your Account ID
  at the top of your AdUnblock dashboard.
</Warning>

## Usage

### Data Mode with Custom Server

Using `server-tag-react-router` in "Data Mode" requires a custom server-side rendering (SSR) setup. The `serverTagLoader` is designed to run exclusively on the server.

#### 1. Define Your Routes (Shared)

This route configuration is used by both the server and the client.

```tsx theme={null}
// app/routes.tsx
import ServerTag, { serverTagLoader } from "@adunblock/server-tag-react-router";

// Your page component
function HomePage() {
  return (
    <div>
      <ServerTag scriptAttributes={{ "data-code": "YOUR_ACCOUNT_ID" }} />
      <h1>Home Page</h1>
    </div>
  );
}

export const routes = [
  {
    path: "/",
    element: <HomePage />,
    loader: () =>
      serverTagLoader({
        remoteUrl: "https://public.adunblocker.com/api/vendor_scripts",
        cacheInterval: 300, // Optional: cache for 5 minutes
      }),
  },
];
```

#### 2. Create a Server Entrypoint

This file contains the server-side rendering logic, typically run in an Express or Node.js environment.

```tsx theme={null}
// entry.server.tsx
import { renderToString } from "react-dom/server";
import {
  createStaticHandler,
  createStaticRouter,
  StaticRouterProvider,
} from "react-router-dom/server";
import { routes } from "./app/routes";

export async function render(req: Request) {
  const { query, dataRoutes } = createStaticHandler(routes);
  const context = await query(req);

  if (context instanceof Response) {
    return context;
  }

  const router = createStaticRouter(dataRoutes, context);
  const html = renderToString(
    <StaticRouterProvider router={router} context={context} />
  );

  return new Response("<!DOCTYPE html>" + html, {
    status: context.statusCode,
    headers: { "Content-Type": "text/html" },
  });
}
```

#### 3. Create a Client Entrypoint

This file hydrates the server-rendered HTML in the browser.

```tsx theme={null}
// entry.client.tsx
import { hydrateRoot } from "react-dom/client";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { routes } from "./app/routes";

// In a full setup, you would pass hydrationData to createBrowserRouter
const router = createBrowserRouter(routes);

hydrateRoot(
  document.getElementById("root")!,
  <RouterProvider router={router} />
);
```

### Framework Mode Usage (Optimal Solution)

For React Router applications using a framework with SSR (e.g., Vite's SSR plugin), `ServerTag` offers a powerful and seamless way to manage both global and per-route scripts.

Simply place the `<ServerTag />` component once in your root layout. It will automatically detect and render scripts loaded from **any active route's loader**, from the root down to the deepest child.

#### Example: Hybrid Approach

This example demonstrates loading a global analytics script from the root and a page-specific charting library for a dashboard page.

**1. Update Your Root Layout**

Place `<ServerTag />` in the `<head>` of your root layout. This single component will handle rendering all scripts.

```tsx theme={null}
// app/root.tsx
import ServerTag, { serverTagLoader } from "@adunblock/server-tag-react-router";
import { Outlet } from "react-router-dom";

export async function loader() {
  // Load global scripts for all pages
  return await serverTagLoader({
    remoteUrl: "https://public.adunblocker.com/api/vendor_scripts",
  });
}

export default function Root() {
  return (
    <html>
      <head>
        <ServerTag scriptAttributes={{ "data-code": "YOUR_ACCOUNT_ID" }} />
        {/* ... other head elements */}
      </head>
      <body>
        <Outlet />
        {/* ... other body elements */}
      </body>
    </html>
  );
}
```

**2. Add a Page-Specific Loader**

In a specific route, add another loader. When combining with other page data, ensure that the object returned by `serverTagLoader` is spread into the final returned object from your loader.

```tsx theme={null}
// routes/dashboard.tsx
import { serverTagLoader } from "@adunblock/server-tag-react-router";

export async function loader() {
  const [scriptData, dashboardData] = await Promise.all([
    // Load scripts only for this page
    serverTagLoader({
      remoteUrl: `https://public.adunblocker.com/api/vendor_scripts`,
    }),
    // Load other page data
    fetch("https://api.example.com/dashboard").then((r) => r.json()),
  ]);

  // Spread the scriptData to make the scripts available
  return { ...scriptData, dashboardData };
}

export default function DashboardPage() {
  // ... page component using dashboardData
  return <div>Dashboard Content</div>;
}
```

## Expected Remote Response Format

The remote URL should return a JSON response in this format:

```json theme={null}
["https://example.com/script1.js", "https://example.com/script2.js"]
```

## Custom Script Rendering

Override the default script rendering with a custom callback:

```tsx theme={null}
import ServerTag from "@adunblock/server-tag-react-router";

function MyPage() {
  return (
    <div>
      <ServerTag
        async={false}
        renderScript={(scripts) => (
          <>
            {scripts.map((src) => (
              <script
                key={src}
                src={src}
                defer
                data-custom-attribute="server-loaded"
              />
            ))}
          </>
        )}
      />
      <h1>My Page Content</h1>
    </div>
  );
}
```

## API Reference

### ServerTag Component

| Prop               | Type               | Default     | Description                                                                                          |
| ------------------ | ------------------ | ----------- | ---------------------------------------------------------------------------------------------------- |
| `async`            | `boolean`          | `true`      | Toggles the `async` attribute on the script tag.                                                     |
| `scriptAttributes` | `ScriptAttributes` | `undefined` | Attributes applied to every generated `<script>` tag. **Must include `data-code: YOUR_ACCOUNT_ID`.** |
| `renderScript`     | `function`         | `undefined` | Custom script rendering function.                                                                    |

### Loader Function

#### `serverTagLoader(config)`

Async function for loading scripts in React Router loaders. Works with both data mode and framework mode.

**Parameters:**

* `config.remoteUrl` (string, required): The URL to fetch script URLs from
* `config.cacheInterval` (number, optional): Cache duration in seconds (default: 300)

**Returns:** `Promise<ServerTagLoaderData>`

**Usage Examples:**

```tsx theme={null}
// Simple loader
export const loader = () =>
  serverTagLoader({
    remoteUrl: "https://public.adunblocker.com/api/vendor_scripts",
  });

// Combined with other data
export async function loader({ params }) {
  const [scripts, data] = await Promise.all([
    serverTagLoader({
      remoteUrl: `https://public.adunblocker.com/api/vendor_scripts`,
      cacheInterval: 600,
    }),
    fetch("/api/data").then((r) => r.json()),
  ]);
  return { scripts, data };
}
```

### Types

```typescript theme={null}
type ScriptAttributeValue = string | boolean | number | undefined;

interface ScriptAttributes {
  [key: string]: ScriptAttributeValue;
}

interface ServerTagProps {
  async?: boolean;
  scriptAttributes?: ScriptAttributes;
  renderScript?: (scripts: string[]) => React.ReactNode;
}

interface ServerTagLoaderArgs {
  remoteUrl: string;
  cacheInterval?: number;
}

interface ServerTagLoaderData {
  scripts: string[];
}
```

## Server-Side Only Design

This package is designed exclusively for server-side rendering:

* **Loaders run on the server** during route resolution
* **Components render on the server** before hydration
* **Scripts are included in the initial HTML** for optimal performance
* **No client-side fetching** or dynamic script injection

## Security

* Only HTTP and HTTPS URLs are allowed
* URL validation prevents malicious protocol usage
* Server-side execution prevents client-side script injection
* Built-in error handling for failed requests

## Browser Compatibility

This package works with all browsers supported by React 19 and React Router DOM 7+ when used in server-side rendering contexts.
