---
title: React integration
description: Consent-gate any third-party markup with @1consent/react — fully static, typed service names, native script timing for returning visitors.
url: https://1consent.app/docs/integration/react
---

# React integration

Add consent management with the `@1consent/react` package. It is pure React and works with server-rendered apps (Next.js App Router with the provider in the root layout, Next.js Pages Router, Remix/React Router, Astro) and client-rendered apps (for example a Vite SPA started with `createRoot`). In server-rendered HTML the CMP script and the consent engine run while the page loads. In a client-rendered app the provider adds them when it mounts, so a returning visitor's gates activate once the CMP script has loaded instead of during page load.

This guide is for websites. For a React Native app, use `@1consent/react-native`: see [Native apps](/docs/integration/native-apps#react-native-with-expo).

**How it works:** wrap any third-party markup in `<OneConsent>`. It renders as an inert `<template>` that cannot execute — no scripts run, no images load, no iframes connect. A tiny inline engine (installed by the provider) resolves it:

- **Returning visitors with valid stored consent** can activate a complete gate when its parse-time resolver runs, using the selected framework and consent epoch from synchronous hosted configuration. Missing, expired or stale consent stays inert until the CMP establishes current permission.
- **First-time visitors** see the consent banner; gated content is released the moment they decide.
- **The server never reads consent.** Your HTML is byte-identical for every visitor, so static rendering, ISR, and CDN caching are fully preserved.

This preserves consent and script dependency order; it does not guarantee execution before first paint. Streamed HTML may paint before a later gate arrives, and external downloads can finish after paint. Blocked or unavailable hosted configuration prevents early activation. SPA gates activate after mounting through the inline engine's observer; they have no initial-paint promise.

For an overview and AI-assisted setup, see [React integration](/integrations/react). Next.js users can follow the dedicated [App Router guide](/docs/integration/nextjs).

## Installation

For a React application:

```bash
npm install --save-exact @1consent/react
```

For a Next.js application, you can use the adapter instead. It exposes the same React API and optional server helpers:

```bash
npm install --save-exact @1consent/nextjs
```

When using the adapter, import the React components and hooks below from `@1consent/nextjs` instead of `@1consent/react`.

## Setup

### Generate typed service names

Run this command from your project directory, replacing `YOUR_APP_ID` with the public site ID from your Dashboard. Type generation reads the site's published frameworks:

```bash
npx @1consent/cli typegen --app YOUR_APP_ID
```

The CLI defaults to the production environment. For a development or local site, add `--env develop` or `--env local` respectively; use the matching `environment` prop on `OneConsentProvider`.

This writes `src/1consent.gen.ts` — or `1consent.gen.ts` at the project root if you have no `src/` directory. Point `--out` anywhere you like to override it. The file contains:

- service and category name maps for `@1consent/react` — the `<OneConsent>` `service` and `category` props autocomplete, and renaming a service in the dashboard becomes a **build-time type error** pointing at the exact JSX usage (`useConsent` accepts any string, so it is not checked),
- `serviceIds` / `categoryIds` — each generated name mapped to its configured id,
- `fastPathVersions` — a framework-ID → structural-version map, so the inline engine can trust the exact framework selected for each visitor. Service and category types are unioned across every published framework.

Re-run after publishing changes to services or categories. In CI, check for stale types without rewriting the file:

```bash
npx @1consent/cli typegen --app YOUR_APP_ID --check
```

### Add the Provider

Wrap your application in your root layout:

```tsx title="app/layout.tsx"
import { OneConsentProvider } from '@1consent/react';
import { fastPathVersions } from '@/1consent.gen';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <OneConsentProvider
          appId="YOUR_APP_ID"
          fastPathVersions={fastPathVersions}
        >
          {children}
        </OneConsentProvider>
      </body>
    </html>
  );
}
```

The provider renders the inline consent engine and loads the CMP (banner + preference center). In Next.js, `appId` falls back to the `NEXT_PUBLIC_1CONSENT_APP_ID` environment variable; in other setups pass `appId` explicitly, because the provider throws when it has no App ID.

`@/1consent.gen` uses your project's own path alias. Next.js projects created with a `src/` directory map `@/` to `src/`, which matches the file `1c typegen` writes to `src/1consent.gen.ts`; Vite has no default alias. If your project has no matching `@/` alias, import the generated file with a relative path instead.

Omitting `fastPathVersions` is safe: `<OneConsent>` gates and `useConsent` still work, but returning visitors lose the parse-time fast path and both wait until the CMP has loaded. (In package versions 0.1.0 and earlier, `useConsent` needs the map; see [Using consent in components](#using-consent-in-components).) The synchronous hosted config selects the visitor's live framework and consent epoch; the generated map only supplies that framework's structural build stamp. A publish that resurfaces consent therefore takes effect without a customer rebuild.

### Wrap third-party scripts

Wrap anything that requires consent — scripts, pixels, iframes, embeds:

```tsx
import { OneConsent } from '@1consent/react';

<OneConsent service="Google Analytics" once>
  <script src="https://www.googletagmanager.com/gtag/js?id=G-XXXXX" />
  <script>{`window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-XXXXX');`}</script>
</OneConsent>
```

Or gate by category:

```tsx
<OneConsent category="Marketing">
  <iframe title="Optional video" src="https://www.youtube.com/embed/dQw4w9WgXcQ" />
</OneConsent>
```

The `service` value matches the service's **name, tag, or id** as configured in your dashboard. With generated types, use the generated name; a tag or id then fails type-checking. Children must be plain HTML elements (they are serialized into inert HTML — React components can't be gated this way; gate the component's own output instead).

**Remount semantics — when to use `once`:** if a `<OneConsent>` unmounts and remounts (SPA navigation, conditional render), its content is promoted again. That is what you want for visual content and UI-rendering scripts — the embed was destroyed with the old mount and must be restored. It is *not* what you want for global side-effect scripts like the gtag loader above, which would execute twice. Add `once` to those: the block then runs at most once per page load, no matter how often it remounts. Never put `once` on visual embeds.

On a page that loads 1Consent with the [script tag](/docs/integration/script-tag) instead of the provider, `<OneConsent>` gates are released by the banner once it has loaded, like the script tag's `<template>` gates, and `useConsent` reports the choice from then on. Neither has a parse-time fast path there.

Place `<OneConsent>` inside `<body>`, after the provider. Its wrapper is a `<div>`, which is invalid inside `<head>` and can cause browser relocation and hydration mismatches. A complete gate can activate during parsing when valid consent and the required hosted configuration are available; its position, streamed arrival and external dependencies still determine execution timing.

## Using consent in components

Access consent state in client components with the `useConsent` hook:

```tsx title="components/personalized-banner.tsx"
'use client';
import { useConsent } from '@1consent/react';

export function PersonalizedBanner() {
  const granted = useConsent('Google Analytics'); // service or category

  if (!granted) return null;

  return <TrackedContent />;
}
```

The hook returns `false` until consent is known and re-renders on consent changes. It reports saved choices only: a toggle in the preferences counts once the visitor saves it.

Consent is known once the CMP has loaded, whether the page loads it with the provider or with the [script tag](/docs/integration/script-tag). With the provider and the generated `fastPathVersions`, a returning visitor's stored choice is known earlier, from the first client render.

Two banner types have limits:

- **IAB TCF:** while the banner or the preferences are open, the hook can report `false` for a saved grant. It reports the choice again when the visitor saves, or on the next page load if they close the preferences without saving.
- **US opt-out:** a visitor who has not saved a choice gets `false` from the hook, while `<OneConsent>` gates follow the banner's default for such visitors.

Use `<OneConsent>` where those limits matter.

In `@1consent/react` and `@1consent/nextjs` 0.1.0 and earlier, the hook reports consent only with the provider and a matching `fastPathVersions` entry; otherwise it stays `false`. Later versions do not need them.

## Provider configuration

| Prop | Type | Default | Description |
|---|---|---|---|
| `appId` | `string` | `NEXT_PUBLIC_1CONSENT_APP_ID` | Your public 1Consent site ID |
| `fastPathVersions` | `Readonly<Record<string, string>>` | — | Framework-ID → build-stamp map from `1consent.gen.ts`; enables the parse-time fast path |
| `nonce` | `string` | — | CSP nonce for the inline engine script |
| `cmpSrc` | `string` | derived from `appId` | Override the CMP embed script URL |
| `environment` | `local \| develop \| production` | `production` | Select a 1Consent service environment (internal setups only) |
| `loadCmp` | `boolean` | `true` | Set `false` when the CMP embed is added elsewhere (e.g. GTM) |

`<OneConsent>` props: exactly one of `service` / `category`, plus optional `nonce` (strict-CSP sites) and `once` (promote at most once per page load — for side-effect scripts that must not re-execute on remount; identical `once` blocks share the guard).

On a site that enforces Trusted Types, allow the `1consent` policy, as described for the [script tag](/docs/integration/script-tag#content-security-policy-with-trusted-types): `trusted-types 1consent 'allow-duplicates'`. The provider and `<OneConsent>` use it when they insert the CMP, the inline engine and gated markup in the browser. A `dangerouslySetInnerHTML` string inside `<OneConsent>` keeps the gate's markup an untrusted string, so pass `TrustedHTML` from your own policy there. Without the `1consent` policy, a client render of `<OneConsent>` throws on a page that enforces Trusted Types.

## Consent semantics

- Gated content only ever transitions **inert → live**. When a visitor revokes previously granted consent, the CMP reloads the page by default (operators can turn this off) — scripts cannot be "un-run".
- If the consent configuration changes structurally (services added/removed), stored consent no longer matches `structuralVersion` and the engine defers to the CMP — visitors are never given scripts they didn't consent to.
- Crawlers and bots (no stored consent) never see gated scripts execute.

## Best practices

- **Commit `1consent.gen.ts`** (or regenerate it in your build step) and add `--check` to CI.
- **Use environment variables** for the site ID to keep it configurable per deployment.
- **Wrap, don't fork:** prefer `<OneConsent>` over conditional rendering with `useConsent` — wrapped content gets the parse-time fast path; hook-gated content always waits for hydration.
