Skip to main content

Server-side snippets

Goal: read the visitor's consent state on your server and decide server-side whether to render a tracking tag at all.

OptSens writes consent in the browser. It mirrors the category state into a cookie named os_consent that your backend can read on the next request.

os_consent holds a URL-encoded JSON object with one short key per category, plus the chosen language:

{ "n": true, "f": true, "an": true, "ad": false, "pf": true, "l": "en" }
KeyCategory
nnecessary
ffunctional
ananalytics
adadvertising
pfperformance
lbanner language

The cookie is set on the registrable domain with SameSite=Lax, and Secure on HTTPS. It carries no timestamp and no personal data. It is not HttpOnly, because the browser script reads it too.

Read it in PHP

<?php
$consent = ['n' => true]; // necessary defaults on
if (!empty($_COOKIE['os_consent'])) {
$decoded = json_decode($_COOKIE['os_consent'], true);
if (is_array($decoded)) {
$consent = $decoded;
}
}

$analyticsAllowed = !empty($consent['an']);
?>
<?php if ($analyticsAllowed): ?>
<!-- render your analytics config tag -->
<?php endif; ?>

Read it in Node

function readOptSensConsent(req) {
const header = req.headers.cookie || '';
const match = header.match(/(?:^|;\s*)os_consent=([^;]+)/);
if (!match) return { n: true };
try {
return JSON.parse(decodeURIComponent(match[1]));
} catch {
return { n: true };
}
}

// const consent = readOptSensConsent(req);
// if (consent.an) { /* render analytics tag */ }

Caveats

  • First visit has no cookie. Treat a missing os_consent as no consent yet: render nothing tracking-related and let the banner appear. Default every non-necessary category to denied.
  • Do not block essential responses on it. The cookie may be absent in Safari Private Browsing, where consent is held in memory for the tab.
  • The cookie is category state only. Granular IAB vendor and purpose choices live in the euconsent-v2 TC string cookie, not here.
  • The browser is the source of truth. Use the server read to avoid rendering a tag at all. For runtime decisions in the page, prefer OptSens.hasConsent('analytics').

Verify

  1. Accept analytics in the banner, then reload the page.
  2. Read os_consent server-side and confirm an is true.
  3. Reject analytics, reload, and confirm an is false and your tag is not rendered.