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
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
```typescript
// 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
```bash
npm install getcookie-sdk
```
Or with yarn:
```bash
yarn add getcookie-sdk
```
## Quick Start
```typescript
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:
```typescript
const client = new GetCookie({
apiKey: process.env.GETCOOKIE_API_KEY
});
```
### Access Token Authentication
For user-context operations:
```typescript
const client = new GetCookie({
accessToken: userToken
});
```
### Login Flow
```typescript
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
```typescript
const newTokens = await client.refreshToken(refreshToken);
```
## Domain Management
### Create Domain
```typescript
const domain = await client.createDomain('example.com');
console.log(domain.id);
```
### List Domains
```typescript
const { items, total } = await client.listDomains(0, 100);
console.log(`${total} domains found`);
```
### Get Domain Details
```typescript
const domain = await client.getDomain('domain-id');
console.log(domain.last_scan_at);
```
### Update Domain
```typescript
const updated = await client.updateDomain('domain-id', {
domain: 'new.example.com'
});
```
### Delete Domain
```typescript
await client.deleteDomain('domain-id');
```
## Cookie Scanning
### Start a Scan
```typescript
const { scan_id, status } = await client.initiateScan('domain-id');
console.log(`Scan ${scan_id} is ${status}`);
```
### Check Scan Status
```typescript
const scan = await client.getScanStatus('scan-id');
if (scan.status === 'completed') {
console.log(`Found ${scan.cookies_found} cookies`);
}
```
### Get Detected Cookies
```typescript
const { items: cookies } = await client.getScanCookies('scan-id');
for (const cookie of cookies) {
console.log(`${cookie.name}: ${cookie.category}`);
}
```
### View Scan History
```typescript
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
```typescript
const updated = await client.updateCookie('cookie-id', {
category: 'analytics',
description: 'Google Analytics tracking cookie'
});
```
## Widget Configuration
### Get Widget Config
```typescript
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
```typescript
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
```typescript
const { snippet } = await client.getWidgetSnippet('domain-id');
console.log(snippet);
//
```
## Consent Analytics
### Get Consent Statistics
```typescript
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
```typescript
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
```typescript
const org = await client.createOrganization('My Agency');
console.log(org.id);
```
### List Organizations
```typescript
const orgs = await client.listOrganizations();
```
### Add Team Member
```typescript
const member = await client.addOrganizationMember(
'org-id',
'
[email protected]',
'editor'
);
```
### List Members
```typescript
const members = await client.listOrganizationMembers('org-id');
```
## API Keys
### Create API Key
```typescript
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
```typescript
const keys = await client.listAPIKeys();
```
### Delete API Key
```typescript
await client.deleteAPIKey('key-id');
```
## Webhooks
### Create Webhook
```typescript
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
```typescript
const webhooks = await client.listWebhooks();
```
### Delete Webhook
```typescript
await client.deleteWebhook('webhook-id');
```
## Error Handling
```typescript
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:
```typescript
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
```typescript
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
```typescript
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
```typescript
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
```typescript
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.