Volver al blog
Technical

GetCookies TypeScript SDK: Programmatic Consent Management

Equipo de GetCookiesDecember 31, 202416 min de lectura
SDKTypeScriptAPIDeveloperIntegration

TLDR: GetCookies SDK is a TypeScript client for programmatic consent management. Full type safety, async/await support, and comprehensive API coverage for building custom integrations, internal tools, and automated workflows.

Read full summary

A fully-typed TypeScript SDK for the GetCookies API that enables developers to programmatically manage domains, run cookie scans, retrieve consent statistics, configure widgets, and integrate consent management into custom applications. Designed for Node.js environments with modern async/await patterns.

Summary by Claude AI

The Custom Dashboard Problem

Illustrative scenario: a composite example, not a specific reported case.

An agency managing 200+ client websites needed more than a standard dashboard. They wanted:

  • Unified reporting across all clients
  • Custom alerting rules
  • Integration with their existing client portal
  • White-label consent analytics

Building on top of a REST API meant writing boilerplate, handling auth, managing types manually. Every endpoint required custom code.

The SDK provides a typed, ergonomic interface that reduces integration time from weeks to hours.

Why Use the SDK?

Type Safety

Full TypeScript definitions mean:

  • Autocomplete for all methods and properties
  • Compile-time error checking
  • Self-documenting code

Ergonomic API

// Without SDK
const response = await fetch('/api/v1/domains/', {
  headers: { Authorization: `Bearer ${token}` }
});
const data = await response.json();
if (!response.ok) throw new Error(data.detail);

// With SDK
const { items } = await client.listDomains();

Error Handling

Typed error classes for different failure modes:

  • AuthenticationError: Token expired or invalid
  • ValidationError: Invalid input data
  • GetCookieError: General API errors

Installation

npm install getcookie-sdk

Or with yarn:

yarn add getcookie-sdk

Quick Start

import GetCookie from 'getcookie-sdk';

// Initialize with API key
const client = new GetCookie({
  apiKey: 'your_api_key'
});

// Or with access token
const client = new GetCookie({
  accessToken: 'your_access_token'
});

// List all domains
const { items: domains } = await client.listDomains();
console.log(domains);

// Start a scan
const scan = await client.initiateScan(domains[0].id);
console.log(`Scan started: ${scan.scan_id}`);

Authentication

API Key Authentication

Best for server-to-server communication:

const client = new GetCookie({
  apiKey: process.env.GETCOOKIE_API_KEY
});

Access Token Authentication

For user-context operations:

const client = new GetCookie({
  accessToken: userToken
});

Login Flow

const client = new GetCookie();

// Login and get tokens
const tokens = await client.login('[email protected]', 'password');
console.log(tokens.access_token);

// Client is now authenticated
const user = await client.getMe();
console.log(user.email);

Token Refresh

const newTokens = await client.refreshToken(refreshToken);

Domain Management

Create Domain

const domain = await client.createDomain('example.com');
console.log(domain.id);

List Domains

const { items, total } = await client.listDomains(0, 100);
console.log(`${total} domains found`);

Get Domain Details

const domain = await client.getDomain('domain-id');
console.log(domain.last_scan_at);

Update Domain

const updated = await client.updateDomain('domain-id', {
  domain: 'new.example.com'
});

Delete Domain

await client.deleteDomain('domain-id');

Cookie Scanning

Start a Scan

const { scan_id, status } = await client.initiateScan('domain-id');
console.log(`Scan ${scan_id} is ${status}`);

Check Scan Status

const scan = await client.getScanStatus('scan-id');

if (scan.status === 'completed') {
  console.log(`Found ${scan.cookies_found} cookies`);
}

Get Detected Cookies

const { items: cookies } = await client.getScanCookies('scan-id');

for (const cookie of cookies) {
  console.log(`${cookie.name}: ${cookie.category}`);
}

View Scan History

const { items: scans } = await client.getScanHistory('domain-id');

for (const scan of scans) {
  console.log(`${scan.created_at}: ${scan.cookies_found} cookies`);
}

Update Cookie Classification

const updated = await client.updateCookie('cookie-id', {
  category: 'analytics',
  description: 'Google Analytics tracking cookie'
});

Widget Configuration

Get Widget Config

const config = await client.getWidgetConfig('domain-id');
console.log(`Position: ${config.position}`);
console.log(`Theme: ${config.theme}`);
console.log(`Consent Mode: ${config.google_consent_mode}`);

Update Widget Config

const updated = await client.updateWidgetConfig('domain-id', {
  position: 'bottom-right',
  theme: 'dark',
  primary_color: '#0066cc',
  google_consent_mode: true,
  iab_tcf_enabled: true,
  block_scripts_before_consent: true
});

Get Embed Snippet

const { snippet } = await client.getWidgetSnippet('domain-id');
console.log(snippet);
// <script src="https://cdn.getcookies.co/widget.js?id=..." async></script>

Consent Analytics

Get Consent Statistics

const stats = await client.getConsentStats('domain-id');

console.log(`Total consents: ${stats.total_consents}`);
console.log(`Accepted: ${stats.accepted}`);
console.log(`Rejected: ${stats.rejected}`);
console.log(`Acceptance rate: ${(stats.acceptance_rate * 100).toFixed(1)}%`);

Get Consent Logs

const { items: logs } = await client.getConsentLogs('domain-id', 0, 100);

for (const log of logs) {
  console.log(`${log.timestamp}: ${log.consent_given ? 'Accepted' : 'Rejected'}`);
}

Organizations

Create Organization

const org = await client.createOrganization('My Agency');
console.log(org.id);

List Organizations

const orgs = await client.listOrganizations();

Add Team Member

const member = await client.addOrganizationMember(
  'org-id',
  '[email protected]',
  'editor'
);

List Members

const members = await client.listOrganizationMembers('org-id');

API Keys

Create API Key

const { api_key, key } = await client.createAPIKey(
  'domain-id',
  'CI/CD Key',
  ['domains:read', 'scans:write']
);
console.log(`Key: ${key}`); // Only shown once!

List API Keys

const keys = await client.listAPIKeys();

Delete API Key

await client.deleteAPIKey('key-id');

Webhooks

Create Webhook

const webhook = await client.createWebhook(
  'domain-id',
  'https://your-api.com/webhooks/consent',
  ['consent.accepted', 'consent.rejected', 'scan.completed']
);
console.log(`Secret: ${webhook.secret}`);

List Webhooks

const webhooks = await client.listWebhooks();

Delete Webhook

await client.deleteWebhook('webhook-id');

Error Handling

import GetCookie, {
  GetCookieError,
  AuthenticationError,
  ValidationError
} from 'getcookie-sdk';

try {
  await client.createDomain('invalid');
} catch (error) {
  if (error instanceof AuthenticationError) {
    // Re-authenticate
    await client.login(email, password);
  } else if (error instanceof ValidationError) {
    // Handle validation errors
    console.error('Invalid input:', error.message);
  } else if (error instanceof GetCookieError) {
    // Handle other API errors
    console.error(`API error (${error.statusCode}): ${error.message}`);
  }
}

TypeScript Types

All types are exported for use in your application:

import type {
  Domain,
  Scan,
  Cookie,
  ConsentLog,
  WidgetConfig,
  Organization,
  OrganizationMember,
  APIKey,
  Webhook,
  ConsentStats,
  TokenResponse,
  UserResponse
} from 'getcookie-sdk';

function processDomain(domain: Domain) {
  console.log(domain.last_scan_at);
}

Real-World Examples

Agency Dashboard

import GetCookie from 'getcookie-sdk';

async function generateAgencyReport() {
  const client = new GetCookie({ apiKey: process.env.GETCOOKIE_API_KEY });

  const { items: domains } = await client.listDomains();

  const report = await Promise.all(
    domains.map(async (domain) => {
      const stats = await client.getConsentStats(domain.id);
      return {
        domain: domain.domain,
        acceptanceRate: stats.acceptance_rate,
        totalConsents: stats.total_consents
      };
    })
  );

  return report.sort((a, b) => b.acceptanceRate - a.acceptanceRate);
}

Automated Scanning Pipeline

import GetCookie from 'getcookie-sdk';

async function runComplianceScan(domainId: string) {
  const client = new GetCookie({ apiKey: process.env.GETCOOKIE_API_KEY });

  // Start scan
  const { scan_id } = await client.initiateScan(domainId);

  // Poll for completion
  let scan = await client.getScanStatus(scan_id);
  while (scan.status === 'pending' || scan.status === 'running') {
    await new Promise(r => setTimeout(r, 5000));
    scan = await client.getScanStatus(scan_id);
  }

  if (scan.status === 'failed') {
    throw new Error(`Scan failed: ${scan.error_message}`);
  }

  // Get results
  const { items: cookies } = await client.getScanCookies(scan_id);
  const unclassified = cookies.filter(c => c.category === 'unclassified');

  return {
    totalCookies: cookies.length,
    unclassifiedCookies: unclassified.length,
    cookies
  };
}

Custom Alerting

import GetCookie from 'getcookie-sdk';

async function checkConsentHealth(domainId: string) {
  const client = new GetCookie({ apiKey: process.env.GETCOOKIE_API_KEY });

  const stats = await client.getConsentStats(domainId);

  if (stats.acceptance_rate < 0.5) {
    // Alert: low acceptance rate
    await sendAlert({
      type: 'low_consent_rate',
      domain: domainId,
      rate: stats.acceptance_rate
    });
  }

  // Check for recent rejections spike
  const { items: logs } = await client.getConsentLogs(domainId, 0, 100);
  const recentRejections = logs.filter(l => !l.consent_given).length;

  if (recentRejections > 80) {
    await sendAlert({
      type: 'rejection_spike',
      domain: domainId,
      rejections: recentRejections
    });
  }
}

Getting Started

  1. Install: npm install getcookie-sdk
  2. Initialize with API key or access token
  3. Start making typed API calls
import GetCookie from 'getcookie-sdk';

const client = new GetCookie({ apiKey: 'your-key' });
const { items } = await client.listDomains();
console.log(items);

Build consent management into your applications with confidence.

Preguntas frecuentes

What TypeScript features does the SDK support?
The SDK provides full type definitions, autocomplete support, compile-time error checking, and exports all types for use in your applications.
How do I authenticate with the SDK?
Initialize with an API key for server-to-server communication or an access token for user-context operations. The SDK handles token refresh automatically.
What operations does the SDK support?
The SDK covers all API operations: domains, scans, cookies, widget config, consent stats, organizations, API keys, and webhooks with full CRUD support.
G

Equipo de GetCookies

Escrito y mantenido por el equipo de GetCookies en Getia AS, en Oslo (Noruega). Este artículo es información general sobre el consentimiento de cookies, no asesoramiento jurídico.

Escanea tu propio sitio gratis

El plan gratuito muestra el banner en un sitio con tres escaneos de cookies al mes. Sin tarjeta, sin llamadas comerciales.