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.
The os_consent cookie
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" }
| Key | Category |
|---|---|
n | necessary |
f | functional |
an | analytics |
ad | advertising |
pf | performance |
l | banner 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_consentas 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-v2TC 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
- Accept analytics in the banner, then reload the page.
- Read
os_consentserver-side and confirmanistrue. - Reject analytics, reload, and confirm
anisfalseand your tag is not rendered.
Related pages
- window.OptSens for the in-page consent checks.
- Consent records for what is stored for audits.
- IAB TCF for the
euconsent-v2TC string.