next-consent-bar
v1.0.0
Published
Consent banner for Next.js that helps with India's DPDP Act and GDPR. Reads consent on the server, loads scripts only after consent, React hooks. Built on consentbar.
Maintainers
Readme
next-consent-bar
A consent banner for Next.js. Users choose what you may use their data for, and can change their mind at any time. 23 languages.
Live demo: try the banner, switch between 23 languages and watch the events.
next-consent-bar is built on consentbar and react-consent-bar. consentbar draws the banner and the preferences panel, saves the user's choice and keeps a record of it. react-consent-bar adds a provider, hooks and components for React. This package adds what Next.js needs on top:
getServerConsent()reads the user's choice from the cookie on the server. The first page the user sees already shows the right content.<ConsentScript>loads a script with Next.js<Script>only after the user agrees.
consentbar is made for India's data protection law: the Digital Personal Data Protection (DPDP) Act, 2023 and the DPDP Rules, 2025. It also works for European-style (GDPR) cookie consent.
Important: next-consent-bar helps you follow the DPDP consent rules. It does not make your website legally compliant on its own. This page is not legal advice.
Features
- No flash of wrong content. The server reads the consent cookie, so pages render with the user's real choice. Content does not jump after the page loads.
- Load scripts only after consent.
<ConsentScript purpose="analytics">takes everynext/scriptprop and renders nothing until the user agrees. - Read consent anywhere on the server: in Server Components, route handlers and middleware.
- Everything from react-consent-bar:
<ConsentBarProvider>,useConsent(),useHasConsent(),<ConsentGate>,<ConsentPlaceholder>and<PrivacyChoicesButton>. - Everything from consentbar: consent per purpose, "Reject all" as easy as "Accept all", English and the 22 languages of the Eighth Schedule, and consent records.
- App Router and Pages Router. Works with Next.js 14, 15 and 16.
- TypeScript types included.
Installation
If your project uses npm:
npm install next-consent-barOr with another package manager:
pnpm add next-consent-bar
yarn add next-consent-bar
bun add next-consent-barconsentbar and react-consent-bar are installed with it. You need Next.js 14 or newer.
Quick start
These steps use the App Router: the app/ folder of Next.js 13.4 and newer. For the pages/ folder, see Pages Router setup.
Set it up in 4 steps
Step 1. Write your config. List your purposes and your contact details. A purpose is one reason you use personal data, such as "Analytics". Put the config in its own file. Do not add 'use client' to it, because the server reads it too:
// consent-config.ts
import type { ConsentBarConfig } from 'next-consent-bar'
export const consentConfig: ConsentBarConfig = {
purposes: [
{ id: 'essential', title: 'Essential', description: 'Keeps you signed in and protects your account.', required: true },
{ id: 'analytics', title: 'Analytics', description: 'Counts visits so we can improve the site.' },
{ id: 'marketing', title: 'Marketing', description: 'Shows videos and offers from other sites.' },
],
notice: {
fiduciaryName: 'Example Pvt Ltd',
privacyPolicyUrl: 'https://example.in/privacy',
contactEmail: '[email protected]',
},
}Step 2. Make a provider component. It runs in the browser, so it starts with 'use client':
// app/consent-provider.tsx
'use client'
import type { ReactNode } from 'react'
import { ConsentBarProvider, type InitialConsent } from 'next-consent-bar'
import { consentConfig } from '../consent-config'
export function ConsentProvider({ initialConsent, children }: { initialConsent: InitialConsent; children: ReactNode }) {
return (
<ConsentBarProvider config={consentConfig} initialConsent={initialConsent}>
{children}
</ConsentBarProvider>
)
}Step 3. Read the cookie in your root layout and wrap your app.
// app/layout.tsx
import type { ReactNode } from 'react'
import { cookies } from 'next/headers'
import { getServerConsent } from 'next-consent-bar/server'
import { consentConfig } from '../consent-config'
import { ConsentProvider } from './consent-provider'
export default async function RootLayout({ children }: { children: ReactNode }) {
const consent = getServerConsent(await cookies(), consentConfig)
return (
<html lang="en">
<body>
<ConsentProvider initialConsent={consent}>{children}</ConsentProvider>
</body>
</html>
)
}Step 4. Use consent in your pages. For example, load Google Analytics only after the user agrees:
// app/analytics.tsx
'use client'
import { ConsentScript } from 'next-consent-bar'
export function Analytics() {
return <ConsentScript purpose="analytics" src="https://www.googletagmanager.com/gtag/js?id=G-XXXX" />
}That's it. The banner shows the first time someone visits. After they choose, it hides, and a small "Privacy choices" button stays in the corner.
Table of contents
Usage
App Router setup
The quick start above is the full App Router setup. Here is why it has these parts.
Server and Client Components. In the App Router, components are Server Components by default. They run only on the server and cannot use hooks or the browser. A Client Component starts with 'use client'. It is rendered on the server first, and then runs in the browser too. Every component and hook in next-consent-bar is a Client Component. next-consent-bar/server is for server code.
Why the separate provider file. The provider needs config, and config must stay the same object between renders. When you import consentConfig inside a Client Component (consent-provider.tsx), it stays the same. It also lets you use functions in your config, such as onConsent, which cannot be sent from a Server Component.
Why read the cookie on the server. consentbar saves the user's choice in a cookie named consentbar. The browser sends this cookie with every request. Without it, the server does not know the user's choice, so it renders every gated part as "no consent". The browser then shows the real content a moment later. This jump is called a flash.
With getServerConsent(), the server reads the cookie and renders the right content at once. The provider uses the same values in the browser for the first render, so hydration (the step where React in the browser takes over the HTML from the server) finds no differences.
cookies() and Next.js versions. In Next.js 15 and 16, cookies() is async, so write await cookies(). In Next.js 14, cookies() is not async: write getServerConsent(cookies(), consentConfig). If you pass the promise by mistake, getServerConsent() throws an error that tells you to add await.
Pass your config as the options. getServerConsent(source, consentConfig) uses cookieName, version, expiresAfterDays and purposes from your config, so the server follows the same rules as the browser. Other config fields are ignored.
Reading cookies makes the page dynamic. Next.js renders a page that reads cookies on every request, instead of once at build time. If you want static pages, skip getServerConsent() and leave out initialConsent. Everything still works, but gated content appears just after the page loads.
Load Google Analytics only after consent
<ConsentScript> renders Next.js <Script> only when the purpose is allowed. It takes every next/script prop: src, id, strategy, onLoad, onReady, onError and inline code as children. Inline scripts need an id.
// app/analytics.tsx
'use client'
import { ConsentScript } from 'next-consent-bar'
const GA_ID = 'G-XXXX'
export function Analytics() {
return (
<>
<ConsentScript purpose="analytics" src={`https://www.googletagmanager.com/gtag/js?id=${GA_ID}`} strategy="afterInteractive" />
<ConsentScript purpose="analytics" id="ga-init" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_ID}');
`}
</ConsentScript>
</>
)
}Add <Analytics /> inside the provider, for example in app/layout.tsx next to {children}:
<ConsentProvider initialConsent={consent}>
{children}
<Analytics />
</ConsentProvider>To need more than one purpose, pass a list: purpose={['analytics', 'marketing']}. Every purpose in it must be allowed.
Strategies. Use afterInteractive (the default) or lazyOnload. The script is added only after consent, so beforeInteractive cannot work. worker is not supported.
Withdrawal. When the user withdraws consent, <ConsentScript> is removed, but a script that already ran keeps running. To stop it, reload the page:
'use client'
import { useEffect } from 'react'
import { useConsent } from 'next-consent-bar'
export function ReloadOnWithdraw() {
const { controller } = useConsent()
useEffect(() => {
if (!controller) return
return controller.on('withdraw', ({ purposes }) => {
if (purposes.includes('analytics')) location.reload()
})
}, [controller])
return null
}Show embeds only after consent
Videos, maps and chat widgets from other sites can collect data as soon as they load. <ConsentGate> keeps them out of the page until the user agrees. <ConsentPlaceholder> shows a short message with an "Allow" button in their place:
'use client'
import { ConsentGate, ConsentPlaceholder } from 'next-consent-bar'
export function ProductVideo() {
return (
<ConsentGate purpose="marketing" fallback={<ConsentPlaceholder purpose="marketing" />}>
<iframe
src="https://www.youtube-nocookie.com/embed/VIDEO_ID"
title="Product video"
width="560"
height="315"
allowFullScreen
/>
</ConsentGate>
)
}You can use <ConsentGate> from a Server Component too, as long as the gate and its children are inside the provider. With initialConsent, the server already renders the iframe for users who allowed "Marketing".
Add a "Privacy choices" button to your footer, so users can change their mind at any time:
import { PrivacyChoicesButton } from 'next-consent-bar'
export function Footer() {
return (
<footer>
<a href="/privacy">Privacy policy</a>
<PrivacyChoicesButton className="footer-link" />
</footer>
)
}The hooks and components are described in full in the react-consent-bar README.
Read consent in a Server Component or route handler
getServerConsent() works in any server code. It takes the result of await cookies(), a Request, a Headers object, or a Cookie header string.
In a Server Component:
// app/offers/page.tsx
import { cookies } from 'next/headers'
import { getServerConsent } from 'next-consent-bar/server'
import { consentConfig } from '../../consent-config'
export default async function OffersPage() {
const consent = getServerConsent(await cookies(), consentConfig)
return consent.purposes.marketing ? <PersonalOffers /> : <GeneralOffers />
}In a route handler (a file like app/api/.../route.ts that answers HTTP requests):
// app/api/recommendations/route.ts
import { getServerConsent, hasConsent } from 'next-consent-bar/server'
import { consentConfig } from '../../../consent-config'
export async function GET(request: Request) {
const consent = getServerConsent(request, consentConfig)
if (!hasConsent(consent, 'marketing')) {
return Response.json({ items: [], personalised: false })
}
return Response.json({ items: ['Item A', 'Item B'], personalised: true })
}The result is plain data:
{
decided: true, // the user made a choice that is still valid
purposes: { essential: true, analytics: true, marketing: false },
noticeVersion: '1',
timestamp: '2026-11-28T10:15:00.000Z',
recordId: '3b1f8c9e-6a2d-4c1e-9b7a-2f0e5d4c3b2a',
language: 'en', // null when there is no cookie
}Read a purpose with consent.purposes.analytics or hasConsent(consent, 'analytics'). There is no consent.hasConsent() method on purpose: Next.js cannot send functions from a Server Component to a Client Component, and plain data can go straight into initialConsent.
Do not trust consent for security. The cookie is set in the browser, so a user can change it. Use it to respect choices, not to protect data.
Pages Router setup
With the pages/ folder, wrap your app in pages/_app.tsx:
// pages/_app.tsx
import type { AppProps } from 'next/app'
import { ConsentBarProvider } from 'next-consent-bar'
import { consentConfig } from '../consent-config'
export default function App({ Component, pageProps }: AppProps) {
return (
<ConsentBarProvider config={consentConfig} initialConsent={pageProps.initialConsent}>
<Component {...pageProps} />
</ConsentBarProvider>
)
}That is enough for the banner, the hooks and the components. To also avoid the flash on a page that is rendered on each request, read the cookie in getServerSideProps:
// pages/index.tsx
import type { GetServerSideProps } from 'next'
import { getServerConsent } from 'next-consent-bar/server'
import { consentConfig } from '../consent-config'
export const getServerSideProps: GetServerSideProps = async ({ req }) => {
return { props: { initialConsent: getServerConsent(req.headers.cookie ?? '', consentConfig) } }
}The provider uses initialConsent only once, for the first page the user opens. After that, the bar is ready in the browser and other pages do not need it.
Middleware
Middleware is code that runs before a request reaches your page. In Next.js 16 it is called proxy (proxy.ts). In older versions it is middleware.ts. Both get a request, so you can read consent there:
// proxy.ts (Next.js 16) or middleware.ts (Next.js 14 and 15)
import { NextResponse, type NextRequest } from 'next/server'
import { getServerConsent } from 'next-consent-bar/server'
import { consentConfig } from './consent-config'
export function proxy(request: NextRequest) {
const consent = getServerConsent(request, consentConfig)
const response = NextResponse.next()
response.headers.set('x-consent-analytics', consent.purposes.analytics ? 'yes' : 'no')
return response
}In middleware.ts, name the function middleware instead of proxy. next-consent-bar/server uses no Node.js-only features, so it also works in the Edge runtime.
API
ConsentScript
<ConsentScript purpose="analytics" src="..." />| Prop | Type | Default | What it does |
|---|---|---|---|
| purpose | string \| string[] | required | The purpose id. With a list, every purpose must be allowed. |
| any next/script prop | ScriptProps | | Passed to <Script>: src, id, strategy, onLoad, onReady, onError, children and the rest. |
Renders nothing until the purpose is allowed. Must be used inside the provider.
getServerConsent(source, options?)
import { getServerConsent } from 'next-consent-bar/server'
function getServerConsent(source: ConsentSource, options?: ServerConsentOptions): ServerConsentReads the consentbar cookie on the server. source can be:
| Source | Example |
|---|---|
| The result of cookies() | getServerConsent(await cookies()) |
| A Request or NextRequest | getServerConsent(request) |
| A Headers object | getServerConsent(await headers()) |
| A Cookie header string | getServerConsent(req.headers.cookie ?? '') |
| null or undefined | Treated as "no cookie". |
| Option | Type | Default | What it does |
|---|---|---|---|
| cookieName | string | 'consentbar' | The cookie name. Must match cookieName in your config. |
| version | string \| number | '1' | Your notice version. A choice saved for another version does not count. |
| expiresAfterDays | number | 365 | A choice older than this does not count. |
| purposes | (string \| Purpose)[] | none | Your purposes. A string is a required purpose id: always true. Pass config.purposes to also find purposes added after the user chose. |
You can pass your whole consentbar config as options.
The result:
| Field | Type | What it does |
|---|---|---|
| decided | boolean | true when the cookie holds a valid choice: same version, not expired, and no new purposes. |
| purposes | Record<string, boolean> | Purpose ids with true or false. Required purposes are true. Without a valid choice, the others are false (or missing, if you did not pass your purposes). |
| noticeVersion | string | The version that was checked. |
| timestamp | string \| null | When the user chose. null without a valid choice. |
| recordId | string \| null | Id of the record of the last choice. null without a valid choice. |
| language | string \| null | The language saved with the choice. null without a cookie. |
It throws a TypeError for an unknown source, for a promise (add await), and for a bad expiresAfterDays. A broken or unreadable cookie counts as "not decided".
hasConsent(consent, purposeId)
import { hasConsent } from 'next-consent-bar/server'
function hasConsent(consent: ServerConsent, purposeId: string): booleanReturns true when the purpose is allowed in a result of getServerConsent(). Unknown ids give false.
From react-consent-bar
next-consent-bar exports everything from react-consent-bar, so you need only one import:
| Export | What it does |
|---|---|
| ConsentBarProvider | Creates the bar in the browser and shares it. Takes config and initialConsent. |
| ConsentBar | Adds the bar without hooks. |
| useConsent() | The user's choices and functions to change them: ready, decided, purposes, hasConsent(), acceptAll(), rejectAll(), update(), withdraw(), openPreferences(), language, setLanguage(), controller. |
| useHasConsent(id) | true when one purpose is allowed. |
| ConsentGate | Shows children only after consent, otherwise fallback. |
| ConsentPlaceholder | A box with a message, an "Allow" button and a "Privacy choices" button. |
| PrivacyChoicesButton | A button that opens the preferences panel. |
| consentChecker(controller) | A function that says if a purpose is allowed, for other libraries. |
See the react-consent-bar README for every prop.
Types
From next-consent-bar: ConsentScriptProps, and every type from react-consent-bar, such as ConsentBarConfig, InitialConsent, UseConsentResult, ConsentSnapshot, ConsentRecord, Purpose and NoticeDetails.
From next-consent-bar/server: ServerConsent, ServerConsentOptions, ServerPurpose, ConsentSource, CookieStoreLike, HeadersLike, RequestLike.
Notes and limitations
- Not legal advice. This package helps with the DPDP consent rules. It does not make your site compliant on its own. See the DPDP checklist in the consentbar README.
storage: 'localStorage'cannot be read on the server. The browser does not send localStorage with requests. With that setting,getServerConsent()always says "not decided". Keep the default cookie storage if you use it.- Use the same settings on both sides. If your config sets
cookieName,versionorexpiresAfterDays, pass the same values togetServerConsent(). Passing your whole config does this for you. - Reading cookies makes pages dynamic. See App Router setup.
beforeInteractiveandworkerdo not work with<ConsentScript>. The script is added only after consent.- Scripts that already ran keep running after a user withdraws consent. Reload the page if needed.
- The cookie is set in the browser. Users can change it. Do not use it to protect data.
- One provider per page. Two providers would show two banners.
- Translations need checking. No native speaker has reviewed consentbar's Indian language texts yet. See Notes and limitations in the consentbar README.
Requirements
- Next.js 14 or newer, with React 18 or newer.
- Node.js 20 or newer.
next-consent-bar/serveralso runs in the Edge runtime. - Works with
importandrequire. TypeScript types included.
Related packages
consentbar comes in three packages. Install only the one that matches your project: react-consent-bar already includes consentbar, and next-consent-bar includes both.
| Package | Use it for |
|---|---|
| consentbar | Any website: plain HTML, WordPress, PHP, Vue, Svelte and more. The banner itself, plus consentbar/server to read consent on any server. |
| react-consent-bar | React apps (Vite, Create React App, Remix): hooks and components such as useConsent(), <ConsentGate> and <PrivacyChoicesButton>. |
| next-consent-bar (this package) | Next.js: everything in react-consent-bar, plus <ConsentScript> and reading consent on the server, so there is no banner flash. |
Also useful: crumbjar, typed cookies that can wait for consent before they are saved.
License
MIT
