---
title: "Read consent on your server"
description: "Read a visitor's consent from the CookieBeam consent cookie in Rails, Django, Flask, Laravel, Node.js, Next.js, Go, Java and .NET."
url: "https://cookiebeam.com/docs/install/server-side"
lang: "en"
last_updated: "2026-11-16"
---

# Read consent on your server

Read a visitor's consent from the CookieBeam consent cookie in Rails, Django, Flask, Laravel, Node.js, Next.js, Go, Java and .NET.

The banner runs in the browser, but plenty of decisions happen on your server: whether a server-rendered page includes a personalized block, whether a route handler forwards an event to an analytics backend, whether a server-side tag fires. Any server language can make those decisions by reading the consent cookie the banner writes. You don't need a CookieBeam package; the snippets below use only each language's standard JSON and URL-decoding functions.

Install the [script tag](https://cookiebeam.com/docs/install/script-tag) in your layout template first. The banner writes the cookie; your server only reads it.

## Before you start

- **The cookie is the visitor's stated preference, not proof.** The banner writes it with JavaScript, so a visitor can read and edit it. Use it to decide what to render or send. Don't use it as evidence of consent; don't use it for access control. For records you can show an auditor, use the consent log (see [Consent records](https://cookiebeam.com/docs/compliance/consent-records)), the `consent.given` [webhook](https://cookiebeam.com/docs/api-reference/webhooks), or the [Consent API](https://cookiebeam.com/docs/api-reference/consent).
- **The first request has no cookie.** The banner hasn't run yet on the first page view. Treat a missing cookie as "no consent" and render the consent-free version. The next request carries whatever the banner stored.
- **Don't share consent-dependent HTML through a cache.** A page whose HTML depends on the cookie must not be stored in a shared cache (a CDN or reverse proxy) under one key for every visitor. Send `Cache-Control: private` on those responses, or vary the cache on the cookie.
- **The page you rendered doesn't change when the visitor does.** When a visitor changes their choice, the banner updates the cookie and fires `cookiebeam:consentUpdate` in the browser (see [Browser API events](https://cookiebeam.com/docs/api-reference/browser-api#events)). If server-rendered content depends on consent, reload or refetch it from that event.

## The consent cookie

| Property | Value |
| --- | --- |
| Name | `cb_cookie` by default. You can rename it under **Banner settings → Consent → Consent cookie**; use your name in every snippet below |
| Path | `/` by default |
| Domain | The current host by default. Set **Domain** to share it across subdomains, see [Cross-domain consent](https://cookiebeam.com/docs/configure/cross-domain-consent) |
| `SameSite` / `Secure` | `Lax` and `Secure` by default, both configurable |
| `HttpOnly` | Never: the banner has to read and write it from JavaScript |
| Lifetime | `Max-Age` set to the banner's consent lifetime, or a regional rule's own lifetime. The browser deletes the cookie when it ends |
| Value | The consent record as JSON, URL-encoded with JavaScript's `encodeURIComponent` |

Most server frameworks URL-decode cookie values for you (Rails, Laravel and `$_COOKIE`, Express with `cookie-parser`, Next.js `cookies()`, Spring's `@CookieValue`). Others hand you the raw value (Django, Go's `net/http`, the Servlet API). You don't need to know which: an encoded value starts with `%7B` and a decoded one starts with `{`, so every snippet decodes only when the value starts with `%`. Decoding twice can corrupt a record, so don't add your own decoding step on top.

If the banner uses **Use Local Storage Instead of Cookies**, there is no cookie and your server can't read the choice.

## The consent record

A decoded cookie looks like this:

```json
{
  "schemaVersion": 2,
  "categories": ["necessary", "analytics"],
  "revision": 3,
  "data": null,
  "consentId": "anonymous",
  "consentTimestamp": "2026-11-02T09:41:12.512Z",
  "lastConsentTimestamp": "2026-11-02T09:41:12.512Z",
  "languageCode": "en",
  "acceptType": "custom",
  "collectedVia": "banner"
}
```

These fields are stable. New optional fields can be added; a breaking change would raise `schemaVersion`.

| Field | Meaning |
| --- | --- |
| `schemaVersion` | `2`. A record without it is an older version 1 record with the same `categories` and `revision` fields. Treat any other value as unknown |
| `categories` | The accepted category ids. Necessary categories are always included. Check category ids, not display names: the defaults are `necessary`, `analytics`, `marketing` and `preferences`, and your banner may define its own (see [Categories and purposes](https://cookiebeam.com/docs/configure/categories-and-purposes)) |
| `revision` | The banner's consent revision when the choice was made. Missing means `0` |
| `consentId` | The `cb1_` identifier when the banner's [consent ID setting](https://cookiebeam.com/docs/configure/consent-id) created one; `'anonymous'` when the setting is off or the choice did not qualify. A returning visitor's cookie may carry a per-visitor UUID from core versions before 0.3.87 until their next consent write. Do not use as a visitor identifier |
| `consentTimestamp`, `lastConsentTimestamp` | ISO 8601 time of the latest save; `firstConsentTimestamp`, when present, is the time of the first choice |
| `languageCode` | The banner language at the time of the choice |
| `acceptType` | `all`, `custom` or `necessary` |
| `services` | Optional map of category id to the accepted service names, when the banner offers per-service choices |
| `collectedVia` | How the record was produced: `banner`, `preferences`, `api`, or a machine-written default: `default_optin`, `default_optout`, `default_notice`, `hidden_autogrant` |
| `isDefaultState` | `true` when the banner wrote a regional default rather than the visitor choosing |
| `isPending` | See the next section. Don't read it on its own |
| `gpcRespected` | `true` when a Global Privacy Control signal shaped the record |
| `usOptOutChoices` | Optional booleans `saleSharing`, `targetedAdvertising`, `sensitiveData`, `profiling` from the US opt-out panel |

Other fields may appear and can change or disappear without notice: `data` (your own values from `setCookieData`, which the banner can drop when the record nears the cookie size limit), `consentMode` (a Google Consent Mode snapshot for tag templates), `purposeConsent` and `jurisdictions`. The cookie doesn't carry an IAB TCF or GPP string.

### Pending records are not consent

In an opt-in region, the banner can write a record before the visitor has chosen. That record has `isPending: true` and grants nothing.

`isPending: true` also appears on machine-written defaults in opt-out and notice regions when Google Consent Mode is on. Those records also have `isDefaultState: true` and a `collectedVia` of `default_optout`, `default_notice` or `hidden_autogrant`, and they do grant their `categories`, exactly as the banner applies them. So the rule is:

- `isPending` is `true`, and the record is **not** (`isDefaultState: true` with `collectedVia` one of `default_optout`, `default_notice`, `hidden_autogrant`): no consent.
- Otherwise: the record's `categories` are in effect.

### Revision: when you ask visitors again

When you turn on **Ask visitors again** in **Banner settings**, save and publish, the banner's consent revision goes up. From then on the banner treats every record with an older `revision` as no consent and asks again. Your server should do the same, or it keeps honoring a choice the banner no longer accepts.

Get the current revision from the published configuration. It needs no API key and is the `version.consentRevision` field of:

```bash
curl "https://cookiebeam.com/api/v1/mobile/config?bannerId=PUBLIC_BANNER_ID"
```

`PUBLIC_BANNER_ID` is the ID in your loader script URL. Add `&env=<slug>` to select an environment; it defaults to `production`. The endpoint is rate limited per client IP, so fetch it at startup or on a timer and cache the number; don't call it on every request. Native mobile apps use the same endpoint to fetch their configuration. See [Mobile apps](https://cookiebeam.com/docs/install/mobile#fetch-the-configuration) for the full response. You can also keep the number in your own configuration and update it when you ask visitors again. Every snippet below lets you skip the check by passing no revision: `null`, `nil`, `None`, or `-1` in Go.

## The algorithm

Every snippet on this page does the same thing:

1. No cookie or an empty value: no consent.
2. If the value starts with `%`, URL-decode it once.
3. Parse it as JSON. A parse error, or anything other than a JSON object: no consent.
4. `categories` must be an array of strings and `consentId` a non-empty string. Otherwise: no consent.
5. `schemaVersion`, when present, must be `2`. Otherwise: no consent.
6. A pending record (see above): no consent.
7. If you know the current revision and the record's `revision` (default `0`) differs: no consent.
8. Otherwise the visitor has accepted the categories in `categories`.

The banner also rejects a record whose `consentTimestamp` is missing, in the future, or older than the consent lifetime; a V2 record (`schemaVersion: 2`) whose `acceptType` is missing or invalid, or whose `collectedVia` is not a recognized collection method; a record that doesn't include every read-only category; invalid `jurisdictions`; or invalid `purposeConsent` entries. The read-only-category check fails for every visitor when you add a necessary category without turning on "Ask visitors again". The snippets leave these checks out. Add them if your server needs the same strictness the banner enforces.

## Node.js and Express

The reference implementation. Save it as a module, for example `lib/cookiebeam-consent.js`. For CommonJS, drop `export` and use `module.exports`.

```js
const DEFAULT_GRANTS = ['default_optout', 'default_notice', 'hidden_autogrant'];

/** Accepted category ids, or null when there is no usable consent. */
export function readCookieBeamConsent(raw, currentRevision = null) {
  if (typeof raw !== 'string' || raw === '') return null;
  let record;
  try {
    record = JSON.parse(raw.startsWith('%') ? decodeURIComponent(raw) : raw);
  } catch {
    return null;
  }
  if (record === null || typeof record !== 'object' || Array.isArray(record)) return null;
  const { categories, consentId } = record;
  if (!Array.isArray(categories) || !categories.every((c) => typeof c === 'string')) return null;
  if (typeof consentId !== 'string' || consentId.trim() === '') return null;
  if (record.schemaVersion !== undefined && record.schemaVersion !== 2) return null;
  const grantingDefault = record.isDefaultState === true && DEFAULT_GRANTS.includes(record.collectedVia);
  if (record.isPending === true && !grantingDefault) return null;
  const revision = typeof record.revision === 'number' ? record.revision : 0;
  if (currentRevision !== null && revision !== currentRevision) return null;
  return new Set(categories);
}
```

With Express and `cookie-parser`:

```js
import express from 'express';
import cookieParser from 'cookie-parser';
import { readCookieBeamConsent } from './lib/cookiebeam-consent.js';

const app = express();
app.use(cookieParser());

app.get('/', (req, res) => {
  const consent = readCookieBeamConsent(req.cookies.cb_cookie, COOKIEBEAM_REVISION);
  res.set('Cache-Control', 'private');
  res.render('home', { showRecommendations: consent?.has('preferences') ?? false });
});
```

## Next.js (App Router)

Use the module above from Server Components and Route Handlers. The default `tsconfig.json` of a Next.js app allows JavaScript imports. `cookies()` from `next/headers` returns the decoded value. Reading cookies makes the route render dynamically, which is what you want for consent-dependent output.

```tsx
// app/page.tsx
import { cookies } from 'next/headers';
import { readCookieBeamConsent } from '@/lib/cookiebeam-consent';

export default async function Page() {
  const cookieStore = await cookies();
  const consent = readCookieBeamConsent(cookieStore.get('cb_cookie')?.value, COOKIEBEAM_REVISION);

  return <main>{consent?.has('marketing') ? <PartnerOffers /> : null}</main>;
}
```

```ts
// app/api/events/route.ts
import { cookies } from 'next/headers';
import { readCookieBeamConsent } from '@/lib/cookiebeam-consent';

export async function POST(request: Request) {
  const consent = readCookieBeamConsent((await cookies()).get('cb_cookie')?.value, COOKIEBEAM_REVISION);
  if (!consent?.has('analytics')) return new Response(null, { status: 204 });
  await forwardToAnalytics(await request.json());
  return new Response(null, { status: 202 });
}
```

## Python: Django and Flask

```python
import json
from urllib.parse import unquote

DEFAULT_GRANTS = {"default_optout", "default_notice", "hidden_autogrant"}

def read_cookiebeam_consent(raw, current_revision=None):
    """Accepted category ids, or None when there is no usable consent."""
    if not raw:
        return None
    try:
        record = json.loads(unquote(raw) if raw.startswith("%") else raw)
    except ValueError:
        return None
    if not isinstance(record, dict):
        return None
    categories = record.get("categories")
    if not isinstance(categories, list) or not all(isinstance(c, str) for c in categories):
        return None
    consent_id = record.get("consentId")
    if not isinstance(consent_id, str) or not consent_id.strip():
        return None
    if "schemaVersion" in record and record["schemaVersion"] != 2:
        return None
    granting_default = record.get("isDefaultState") is True and record.get("collectedVia") in DEFAULT_GRANTS
    if record.get("isPending") is True and not granting_default:
        return None
    revision = record.get("revision")
    if isinstance(revision, bool) or not isinstance(revision, (int, float)):
        revision = 0
    if current_revision is not None and revision != current_revision:
        return None
    return set(categories)
```

Django:

```python
def home(request):
    consent = read_cookiebeam_consent(request.COOKIES.get("cb_cookie"), COOKIEBEAM_REVISION) or set()
    response = render(request, "home.html", {"show_recommendations": "preferences" in consent})
    response["Cache-Control"] = "private"
    return response
```

Flask:

```python
@app.get("/")
def home():
    consent = read_cookiebeam_consent(request.cookies.get("cb_cookie"), COOKIEBEAM_REVISION) or set()
    return render_template("home.html", show_recommendations="preferences" in consent)
```

## Ruby on Rails

Save as `app/lib/cookie_beam_consent.rb` (or anywhere Rails autoloads):

```ruby
require "json"
require "uri"

module CookieBeamConsent
  DEFAULT_GRANTS = %w[default_optout default_notice hidden_autogrant].freeze

  # Accepted category ids, or nil when there is no usable consent.
  def self.read(raw, current_revision = nil)
    return nil if raw.nil? || raw.empty?
    record = JSON.parse(raw.start_with?("%") ? URI.decode_www_form_component(raw) : raw)
    return nil unless record.is_a?(Hash)
    categories = record["categories"]
    return nil unless categories.is_a?(Array) && categories.all? { |c| c.is_a?(String) }
    consent_id = record["consentId"]
    return nil unless consent_id.is_a?(String) && !consent_id.strip.empty?
    return nil if record.key?("schemaVersion") && record["schemaVersion"] != 2
    granting_default = record["isDefaultState"] == true && DEFAULT_GRANTS.include?(record["collectedVia"])
    return nil if record["isPending"] == true && !granting_default
    revision = record["revision"].is_a?(Numeric) ? record["revision"] : 0
    return nil if current_revision && revision != current_revision
    categories
  rescue JSON::ParserError, ArgumentError
    nil
  end
end
```

In a controller, and in views through the helper:

```ruby
class ApplicationController < ActionController::Base
  helper_method :consented_to?

  private

  def consented_to?(category)
    @cookiebeam_consent ||= CookieBeamConsent.read(cookies[:cb_cookie], COOKIEBEAM_REVISION) || []
    @cookiebeam_consent.include?(category)
  end
end
```

## PHP and Laravel

PHP 8.1 or later:

```php
/** Accepted category ids, or null when there is no usable consent. */
function cookiebeam_consent(mixed $raw, ?int $currentRevision = null): ?array
{
    if (!is_string($raw) || $raw === '') {
        return null;
    }
    $record = json_decode(str_starts_with($raw, '%') ? rawurldecode($raw) : $raw, true);
    if (!is_array($record) || array_is_list($record)) {
        return null;
    }
    $categories = $record['categories'] ?? null;
    if (!is_array($categories) || !array_is_list($categories)) {
        return null;
    }
    foreach ($categories as $category) {
        if (!is_string($category)) {
            return null;
        }
    }
    $consentId = $record['consentId'] ?? null;
    if (!is_string($consentId) || trim($consentId) === '') {
        return null;
    }
    if (array_key_exists('schemaVersion', $record) && $record['schemaVersion'] !== 2) {
        return null;
    }
    $grantingDefault = ($record['isDefaultState'] ?? null) === true
        && in_array($record['collectedVia'] ?? null, ['default_optout', 'default_notice', 'hidden_autogrant'], true);
    if (($record['isPending'] ?? null) === true && !$grantingDefault) {
        return null;
    }
    $revision = is_int($record['revision'] ?? null) ? $record['revision'] : 0;
    if ($currentRevision !== null && $revision !== $currentRevision) {
        return null;
    }
    return $categories;
}
```

Plain PHP: `cookiebeam_consent($_COOKIE['cb_cookie'] ?? null, COOKIEBEAM_REVISION)`.

Laravel encrypts every cookie by default and returns `null` for one it can't decrypt. The banner's cookie isn't encrypted, so exclude it. In Laravel 11 and later, in `bootstrap/app.php`:

```php
->withMiddleware(function (Middleware $middleware) {
    $middleware->encryptCookies(except: ['cb_cookie']);
})
```

In Laravel 10 and earlier, add `'cb_cookie'` to `$except` in `app/Http/Middleware/EncryptCookies.php`. Then:

```php
$consent = cookiebeam_consent($request->cookie('cb_cookie'), config('services.cookiebeam.revision')) ?? [];
$showRecommendations = in_array('preferences', $consent, true);
```

## Go

```go
package consent

import (
	"encoding/json"
	"net/http"
	"net/url"
	"strings"
)

var defaultGrants = map[string]bool{"default_optout": true, "default_notice": true, "hidden_autogrant": true}

// Read returns the accepted category ids, or nil when there is no usable consent.
// Pass a negative currentRevision to skip the revision check.
func Read(r *http.Request, currentRevision int) map[string]bool {
	c, err := r.Cookie("cb_cookie")
	if err != nil {
		return nil
	}
	return Parse(c.Value, currentRevision)
}

func Parse(raw string, currentRevision int) map[string]bool {
	if raw == "" {
		return nil
	}
	if strings.HasPrefix(raw, "%") {
		decoded, err := url.PathUnescape(raw)
		if err != nil {
			return nil
		}
		raw = decoded
	}
	var record map[string]any
	if json.Unmarshal([]byte(raw), &record) != nil || record == nil {
		return nil
	}
	list, ok := record["categories"].([]any)
	if !ok {
		return nil
	}
	categories := make(map[string]bool, len(list))
	for _, c := range list {
		s, ok := c.(string)
		if !ok {
			return nil
		}
		categories[s] = true
	}
	if id, ok := record["consentId"].(string); !ok || strings.TrimSpace(id) == "" {
		return nil
	}
	if v, present := record["schemaVersion"]; present && v != float64(2) {
		return nil
	}
	collectedVia, _ := record["collectedVia"].(string)
	grantingDefault := record["isDefaultState"] == true && defaultGrants[collectedVia]
	if record["isPending"] == true && !grantingDefault {
		return nil
	}
	revision, _ := record["revision"].(float64)
	if currentRevision >= 0 && revision != float64(currentRevision) {
		return nil
	}
	return categories
}
```

A `nil` map answers `false` for every category, so a handler can check `consent.Read(r, revision)["analytics"]` directly.

## Java and Spring

Uses Jackson, which Spring Boot includes:

```java
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;

public final class CookieBeamConsent {
  private static final ObjectMapper JSON = new ObjectMapper();
  private static final Set<String> DEFAULT_GRANTS = Set.of("default_optout", "default_notice", "hidden_autogrant");

  /** Accepted category ids, or null when there is no usable consent. Pass null to skip the revision check. */
  public static Set<String> read(String raw, Integer currentRevision) {
    if (raw == null || raw.isEmpty()) return null;
    try {
      JsonNode record = JSON.readTree(raw.startsWith("%") ? URLDecoder.decode(raw, StandardCharsets.UTF_8) : raw);
      if (record == null || !record.isObject()) return null;
      JsonNode list = record.path("categories");
      if (!list.isArray()) return null;
      Set<String> categories = new HashSet<>();
      for (JsonNode c : list) {
        if (!c.isTextual()) return null;
        categories.add(c.asText());
      }
      JsonNode consentId = record.path("consentId");
      if (!consentId.isTextual() || consentId.asText().isBlank()) return null;
      if (record.has("schemaVersion")) {
        JsonNode schema = record.get("schemaVersion");
        if (!schema.isNumber() || schema.asDouble() != 2) return null;
      }
      JsonNode collectedVia = record.path("collectedVia");
      boolean grantingDefault = isTrue(record.path("isDefaultState"))
          && collectedVia.isTextual() && DEFAULT_GRANTS.contains(collectedVia.asText());
      if (isTrue(record.path("isPending")) && !grantingDefault) return null;
      JsonNode revision = record.path("revision");
      double rev = revision.isNumber() ? revision.asDouble() : 0;
      if (currentRevision != null && rev != currentRevision) return null;
      return categories;
    } catch (IOException | IllegalArgumentException e) {
      return null;
    }
  }

  private static boolean isTrue(JsonNode node) {
    return node.isBoolean() && node.booleanValue();
  }
}
```

In a Spring MVC controller:

```java
@GetMapping("/")
public String home(@CookieValue(name = "cb_cookie", required = false) String cbCookie, Model model) {
  Set<String> consent = CookieBeamConsent.read(cbCookie, cookieBeamRevision);
  model.addAttribute("showRecommendations", consent != null && consent.contains("preferences"));
  return "home";
}
```

## .NET (ASP.NET Core)

```csharp
using System.Text.Json;

public static class CookieBeamConsent
{
    static readonly HashSet<string> DefaultGrants = new() { "default_optout", "default_notice", "hidden_autogrant" };

    // Accepted category ids, or null when there is no usable consent. Pass null to skip the revision check.
    public static HashSet<string>? Read(string? raw, int? currentRevision = null)
    {
        if (string.IsNullOrEmpty(raw)) return null;
        try
        {
            using var doc = JsonDocument.Parse(raw.StartsWith('%') ? Uri.UnescapeDataString(raw) : raw);
            var record = doc.RootElement;
            if (record.ValueKind != JsonValueKind.Object) return null;
            if (!record.TryGetProperty("categories", out var list) || list.ValueKind != JsonValueKind.Array) return null;
            var categories = new HashSet<string>();
            foreach (var c in list.EnumerateArray())
            {
                if (c.ValueKind != JsonValueKind.String) return null;
                categories.Add(c.GetString()!);
            }
            if (!record.TryGetProperty("consentId", out var id) || id.ValueKind != JsonValueKind.String
                || string.IsNullOrWhiteSpace(id.GetString())) return null;
            if (record.TryGetProperty("schemaVersion", out var schema)
                && !(schema.ValueKind == JsonValueKind.Number && schema.TryGetDouble(out var sv) && sv == 2)) return null;
            var grantingDefault = IsTrue(record, "isDefaultState")
                && record.TryGetProperty("collectedVia", out var via) && via.ValueKind == JsonValueKind.String
                && DefaultGrants.Contains(via.GetString()!);
            if (IsTrue(record, "isPending") && !grantingDefault) return null;
            var revision = record.TryGetProperty("revision", out var rev) && rev.ValueKind == JsonValueKind.Number
                && rev.TryGetDouble(out var rv) ? rv : 0.0;
            if (currentRevision is int expected && revision != expected) return null;
            return categories;
        }
        catch (JsonException)
        {
            return null;
        }
    }

    static bool IsTrue(JsonElement record, string name) =>
        record.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.True;
}
```

In a minimal API or controller:

```csharp
var consent = CookieBeamConsent.Read(httpContext.Request.Cookies["cb_cookie"], cookieBeamRevision);
var showRecommendations = consent?.Contains("preferences") ?? false;
```

## Global Privacy Control

The banner reads `navigator.globalPrivacyControl` and applies it according to your [privacy signal settings](https://cookiebeam.com/docs/configure/privacy-signals) and regional rules. Where it applies, the stored record already has the covered categories removed and carries `gpcRespected: true`, so the snippets above need no extra step for it.

The standard banner runtime handles GPC entirely in the browser, but CookieBeam's AMP consent endpoints (`/api/amp/consent/{bannerId}`) do read the `Sec-GPC: 1` request header to set the initial consent state for AMP pages. Outside AMP, browsers that set the signal send `Sec-GPC: 1` with every request, which lets your server see it on the first page view, before the banner has run. Whether your server must treat it as an opt-out, and for which processing, depends on the laws that apply to you; if it should, check the header next to the cookie.

## Verify

1. Open your site, make a choice in the banner, and reload.
2. In the browser's developer tools, under **Application → Cookies** (or **Storage → Cookies**), find `cb_cookie` and check that `categories` lists what you accepted.
3. Request a page from your server with that cookie and check that the consent-dependent output matches. Then change your choice to necessary only, reload, and check again.
4. Turn on **Ask visitors again**, publish, update your revision, and check that your server treats the old cookie as no consent until you choose again.
