How-To

Next.js Privacy Compliance: GDPR Guide for Developers (2026)

·10 min read

Next.js gives you server components, middleware, and full-stack control — which makes GDPR compliance both more powerful and more complex than traditional SPAs. This guide covers Next.js-specific patterns for privacy-by-design, cookie consent, third-party script management, and server-side data handling.

Next.js Privacy Advantages

Next.js has architectural features that uniquely benefit privacy compliance:

  • Server Components: Process data server-side without exposing it to the client
  • Middleware: Intercept requests before they reach your app — perfect for consent enforcement
  • Script component: Conditional loading of third-party scripts with strategy control
  • Route handlers: Server-side API endpoints that keep sensitive logic off the client
  • Edge runtime: Process data closer to users for potential data residency compliance

GDPR Compliance Architecture for Next.js

The ideal Next.js privacy architecture uses a belt-and-suspenders approach: server-side enforcement via middleware plus client-side consent management:

LayerWhat It DoesNext.js Feature
MiddlewareReads consent cookie; strips tracking headersmiddleware.ts
Server ComponentsConditionally renders content based on consentRSC
Client ComponentsRenders consent banner; manages consent state"use client"
Script ComponentConditionally loads third-party scriptsnext/script
Route HandlersProcesses consent changes server-sideapp/api/

1. Cookie Consent with Next.js Middleware

Next.js middleware runs before every request. Use it to read the consent cookie and enforce privacy at the edge:

  • Create middleware.ts in your project root
  • Read the consent cookie from the incoming request
  • If no consent has been given, strip tracking-related cookies from the response
  • Set security headers (CSP, Permissions-Policy) that block tracking by default
  • This ensures tracking is blocked even if client-side JavaScript fails

Key middleware patterns:

  • Parse the consent cookie (JSON with categories: {analytics: false, marketing: false})
  • If analytics consent is not granted, delete GA cookies from the request
  • If marketing consent is not granted, delete ad platform cookies
  • Always allow essential cookies (session, CSRF, consent preference itself)

2. Consent Banner as a Client Component

The consent banner must be a client component because it needs interactivity. Best practices:

  • Create a <ConsentBanner /> client component
  • Store consent preferences in a cookie (not localStorage — middleware can't read localStorage)
  • Use cookies().set() in a Server Action or API route for secure, HttpOnly cookies
  • Provide granular choices: Essential (always on), Analytics, Marketing, Functional
  • Include both "Accept All" and "Reject All" buttons at the same visual level
  • Remember: don't pre-check any optional categories

3. Conditional Script Loading with next/script

The Next.js Script component supports strategies (beforeInteractive, afterInteractive, lazyOnload). Combine this with consent state:

  • Create a client component that reads consent state
  • Only render <Script> tags when the corresponding consent category is granted
  • Use strategy="lazyOnload" for non-essential scripts to improve performance
  • When consent is revoked, remove the scripts and delete their cookies

Common scripts to conditionally load:

ScriptConsent CategoryStrategy
Google Analytics (GA4)AnalyticsafterInteractive
Meta PixelMarketinglazyOnload
Google AdsMarketinglazyOnload
Hotjar / FullStoryAnalyticslazyOnload
Intercom / CrispFunctionalafterInteractive
Stripe.jsEssentialbeforeInteractive

4. Privacy-By-Design Patterns

Next.js's architecture naturally supports privacy by design principles:

  • Data minimization: Use Server Components to process and filter data server-side. Only send the minimum necessary data to client components.
  • Purpose limitation: Use separate API routes for different purposes. Don't mix analytics and core functionality endpoints.
  • Storage limitation: Implement automatic data cleanup in your database with scheduled tasks or cron jobs.
  • Integrity: Validate all user input in Server Actions and route handlers. Use Zod schemas for type-safe validation.

5. Server-Side Data Subject Rights

Implement GDPR data subject rights through API routes:

  • Right of access: Create an API route that compiles all personal data for a user and returns it as JSON or CSV
  • Right to erasure: Create a deletion endpoint that removes data from all tables and notifies third-party processors
  • Right to portability: Export user data in machine-readable format (JSON) via a dedicated endpoint
  • Consent withdrawal: Use a Server Action to clear consent preferences and trigger cookie cleanup

6. Security Headers via next.config.js

Configure security headers in next.config.js to enforce privacy at the HTTP level:

  • Content-Security-Policy: Restrict which scripts and connections are allowed
  • Permissions-Policy: Disable camera, microphone, geolocation by default
  • Referrer-Policy: Set to strict-origin-when-cross-origin to limit referrer leakage
  • X-Content-Type-Options: nosniff to prevent MIME sniffing
  • Strict-Transport-Security: Enforce HTTPS

7. Common Next.js Privacy Pitfalls

  • next/image with external domains: Each external image domain you whitelist sends user IP to that domain. Minimize external domains.
  • next/font/google: Loads fonts from Google servers at build time (safe) — not at runtime like a <link> tag. This is privacy-friendly.
  • Environment variables: NEXT_PUBLIC_ variables are exposed to the client. Never put API keys or secrets in public env vars.
  • Error tracking (Sentry): Captures user data in error reports. Configure PII scrubbing and require consent for non-essential capture.
  • NextAuth.js: Sets session cookies — these are essential and don't need consent, but document them in your privacy policy.
  • ISR/SSG pages: Statically generated pages don't process personal data at generation time, but client-side scripts still do.

8. Recommended Libraries

PurposeLibraryWhy
Cookie consentcookies-next, js-cookieRead/write consent cookies in both server and client
Schema validationZodValidate DSAR request data in route handlers
Privacy analyticsPlausible, UmamiCookie-free, GDPR-friendly alternatives to GA
EmailResend, React EmailSend DSAR confirmation emails with proper templates

Next Steps

After implementing these patterns, test your Next.js application's privacy compliance. PrivacyChecker scans your deployed site for cookies, trackers, security headers, and privacy policy completeness — detecting common Next.js issues like exposed tracking scripts and missing consent management.

Check your website now — free

Run a complete privacy audit in under 60 seconds. Get your score, find issues, and learn how to fix them.

Start Free Audit