Docs menu

Server-side reading

The CookieHug consent cookie format and server-side reading: PHP, Node.js, Python and C# examples.

Server-side Usage

CookieHug sets an HTTP cookie (CookieHugConsent) alongside localStorage, allowing you to check consent state on the server.

PHP

if (isset($_COOKIE['CookieHugConsent'])) {
    $consent = json_decode(
        urldecode($_COOKIE['CookieHugConsent']), true
    );

    if ($consent && $consent['statistics']) {
        // User consented to statistics
        echo '<script src="https://www.googletagmanager.com/gtag/js?id=G-XXXXX"></script>';
    }

    if ($consent && $consent['marketing']) {
        // User consented to marketing
    }
} else {
    // No consent yet — do not load tracking scripts
}

Node.js (Express)

const cookieParser = require('cookie-parser');
app.use(cookieParser());

app.get('/', (req, res) => {
  const raw = req.cookies.CookieHugConsent;
  if (raw) {
    const consent = JSON.parse(decodeURIComponent(raw));

    if (consent.statistics) {
      // Render analytics script server-side
    }
    if (consent.marketing) {
      // Render marketing pixels server-side
    }
  }

  res.render('index');
});

Python (Django)

import json
from urllib.parse import unquote

def index(request):
    raw = request.COOKIES.get('CookieHugConsent')
    if raw:
        consent = json.loads(unquote(raw))

        if consent.get('statistics'):
            # Render analytics
            pass
        if consent.get('marketing'):
            # Render marketing
            pass

    return render(request, 'index.html')

C# (ASP.NET)

var raw = Request.Cookies["CookieHugConsent"];
if (!string.IsNullOrEmpty(raw))
{
    var consent = JsonSerializer.Deserialize<CookieHugConsent>(
        Uri.UnescapeDataString(raw)
    );

    if (consent.Statistics)
    {
        // Render analytics server-side
    }
}