akamai-edge-delivery-polyfill
v1.0.8
Published
Polyfill to make Akamai EdgeWorkers compatible with Cloudflare Workers API for Optimizely Edge Delivery SDK
Downloads
62
Maintainers
Readme
Akamai Edge Delivery Polyfill
A comprehensive polyfill that makes Akamai EdgeWorkers compatible with Cloudflare Workers API, enabling the use of Optimizely Edge Delivery SDK and other Cloudflare-compatible libraries on Akamai's edge platform.
Features
- Request/Response API: Full Fetch API compatibility for handling HTTP requests and responses
- Headers API: Complete Headers implementation matching Web standards
- KVNamespace: Maps Cloudflare KV operations to Akamai EdgeKV
- Crypto API: Web Crypto API polyfill for cryptographic operations
- TextEncoder/TextDecoder: Text encoding/decoding utilities
- ReadableStream: Basic stream implementation for body handling
Installation
npm install akamai-edge-delivery-polyfillBuilding
Build the Package
# Install dependencies
npm install
# Build all bundles
npm run buildThis creates:
dist/index.js- ESM bundle for module importsdist/polyfill.global.js- Global IIFE bundle that auto-installs polyfillsdist/request.js,dist/response.js, etc. - Individual module bundles- TypeScript declarations in
dist/*.d.ts
Build Output
dist/
├── index.js # ESM bundle (main)
├── polyfill.global.js # Global bundle (auto-installs APIs)
├── request.js # Individual modules
├── response.js
├── kv-namespace.js
├── crypto.js
└── *.d.ts # TypeScript declarationsUsage
Option 1: Global Bundle (Easiest - Recommended)
The global bundle automatically installs all polyfills when loaded, making them available globally.
// Import the global bundle first (auto-installs all APIs)
import './node_modules/akamai-edge-delivery-polyfill/dist/polyfill.global.js';
// Now Request, Response, Headers, crypto, etc. are global
export async function onClientRequest(request) {
const cfRequest = new Request(request);
const response = Response.json({
message: 'Hello from Akamai!',
url: cfRequest.url
});
return {
status: response.status,
headers: Object.fromEntries(response.headers.entries()),
body: await response.text()
};
}Option 2: ES Modules
Use the ESM bundle for module imports:
import { Request, Response, installGlobalPolyfills } from 'akamai-edge-delivery-polyfill';
// Use classes directly
export async function onClientRequest(request) {
const cfRequest = new Request(request);
const response = new Response(JSON.stringify({ message: 'Hello from Akamai!' }), {
status: 200,
headers: {
'Content-Type': 'application/json'
}
});
return {
status: response.status,
headers: Object.fromEntries(response.headers.entries()),
body: await response.text()
};
}
// Option 2: Install global polyfills (useful for libraries expecting global APIs)
installGlobalPolyfills();Using with Optimizely Edge Delivery SDK
import { installGlobalPolyfills, KVNamespace } from 'akamai-edge-delivery-polyfill';
import { createInstance } from '@optimizely/edge-delivery-sdk';
// Install global polyfills for Optimizely SDK compatibility
installGlobalPolyfills();
// Create KV namespace for Optimizely data
const optimizelyKV = new KVNamespace('optimizely', 'config');
// Initialize Optimizely
const optimizely = createInstance({
sdkKey: 'your-sdk-key',
// ... other config
});
export async function onClientRequest(request) {
const cfRequest = new Request(request);
// Use Optimizely for decision making
const user = {
id: cfRequest.headers.get('user-id') || 'anonymous',
};
const decision = optimizely.decide(user, 'feature-flag-key');
// Return personalized response
const response = new Response(JSON.stringify({
enabled: decision.enabled,
variables: decision.variables,
}), {
status: 200,
headers: { 'Content-Type': 'application/json' }
});
return {
status: response.status,
headers: Object.fromEntries(response.headers.entries()),
body: await response.text()
};
}KVNamespace (EdgeKV Integration)
import { KVNamespace } from 'akamai-edge-delivery-polyfill';
// Create a KV namespace (maps to Akamai EdgeKV)
const myKV = new KVNamespace('my-namespace', 'production');
// Get a value
const value = await myKV.get('key');
const jsonValue = await myKV.get('key', 'json');
// Put a value
await myKV.put('key', 'value');
await myKV.put('key', JSON.stringify({ data: 'value' }));
// Delete a value
await myKV.delete('key');Crypto API
import { Crypto } from 'akamai-edge-delivery-polyfill';
const crypto = new Crypto();
// Generate random UUID
const uuid = crypto.randomUUID();
// Generate random values
const array = new Uint8Array(16);
crypto.getRandomValues(array);
// Use SubtleCrypto for hashing (if supported by runtime)
const data = new TextEncoder().encode('Hello World');
const hash = await crypto.subtle.digest('SHA-256', data);Helper Functions
import { toEdgeWorkerResponse } from 'akamai-edge-delivery-polyfill';
// Convert Cloudflare-style Response to Akamai EdgeWorker format
const cfResponse = new Response('Hello', { status: 200 });
const ewResponse = await toEdgeWorkerResponse(cfResponse);
// Returns: { status: 200, headers: {...}, body: 'Hello' }API Reference
Request
Wraps Akamai EdgeWorker requests to provide Cloudflare-compatible Request interface.
Constructor:
new Request(input: string | Request | AkamaiRequest, init?: RequestInit)Properties:
url: string- The request URLmethod: string- HTTP methodheaders: Headers- Request headersbodyUsed: boolean- Whether body has been consumed
Methods:
text(): Promise<string>- Read body as textjson(): Promise<any>- Read body as JSONarrayBuffer(): Promise<ArrayBuffer>- Read body as ArrayBufferclone(): Request- Clone the request
Response
Creates Cloudflare-compatible Response objects.
Constructor:
new Response(body?: BodyInit | null, init?: ResponseInit)Properties:
status: number- HTTP status codestatusText: string- HTTP status textok: boolean- True if status is 2xxheaders: Headers- Response headersbody: ReadableStream | null- Response body streambodyUsed: boolean- Whether body has been consumed
Methods:
text(): Promise<string>- Read body as textjson(): Promise<any>- Read body as JSONarrayBuffer(): Promise<ArrayBuffer>- Read body as ArrayBufferclone(): Response- Clone the response
Static Methods:
Response.json(data: any, init?: ResponseInit): Response- Create JSON responseResponse.redirect(url: string, status?: number): Response- Create redirect response
KVNamespace
Maps Cloudflare KV operations to Akamai EdgeKV.
Constructor:
new KVNamespace(namespace: string, group?: string)Methods:
get(key: string, type?: 'text' | 'json' | 'arrayBuffer' | 'stream'): Promise<any>- Get valuegetWithMetadata<T>(key: string, type?): Promise<{ value: any, metadata: T }>- Get with metadataput(key: string, value: string | ArrayBuffer | ReadableStream): Promise<void>- Put valuedelete(key: string): Promise<void>- Delete valuelist(options?: KVListOptions): Promise<KVListResult>- List keys (limited support)
Crypto
Web Crypto API polyfill.
Methods:
getRandomValues<T extends ArrayBufferView>(array: T): T- Fill array with random valuesrandomUUID(): string- Generate random UUIDsubtle: SubtleCrypto- Access SubtleCrypto API
Important Notes
EdgeKV Setup
To use KVNamespace, you need to have Akamai EdgeKV configured and the edgekv.js helper library available in your EdgeWorker bundle. The polyfill expects to require it as:
const { EdgeKV } = require('./edgekv.js');Limitations
- KVNamespace.list(): EdgeKV doesn't natively support listing keys, so this method has limited functionality
- ReadableStream: Basic implementation provided; may not support all stream features
- Crypto.subtle: Some operations may not be available depending on Akamai runtime capabilities
TypeScript Support
The polyfill includes full TypeScript definitions. No additional @types packages needed.
Examples
See the examples/ directory for complete working examples:
basic-usage.ts- Basic request/response handlingoptimizely-integration.ts- Using with Optimizely Edge Delivery SDKkv-storage.ts- EdgeKV integration examples
License
MIT
Contributing
Contributions are welcome! Please open an issue or submit a pull request.
Support
For issues specific to this polyfill, please open a GitHub issue.
For Akamai EdgeWorkers support, see Akamai EdgeWorkers documentation
For Optimizely Edge Delivery SDK support, see Optimizely documentation
