Skip to main content

Overview

This guide covers everything you need to protect your Cloudflare Workers with Unkey’s globally distributed verification. Perfect for edge APIs, serverless functions, and globally distributed applications. What you’ll learn:
  • Quick setup with @unkey/api
  • Using Hono for better routing
  • Reusable middleware patterns
  • Permission-based access control
  • Durable Objects integration
  • Deployment best practices

Prerequisites

Quick Start

1

Create a Cloudflare Worker

2

Install Unkey SDK

3

Configure secrets

Add your root key as a secret:
Enter your root key when prompted.
4

Create a basic worker

src/index.ts
5

Deploy

6

Test it

Create a test key in your Unkey dashboard, then:

Using Hono for Better Routing

For a cleaner routing experience, use Hono:
src/index.ts

Reusable Middleware

Create a clean middleware pattern:
src/middleware/auth.ts
Use it:
src/index.ts

Rate Limit Headers

Add standard rate limit headers to responses:
src/middleware/auth.ts

Durable Objects Integration

For stateful applications with Durable Objects:
src/index.ts
Update wrangler.toml:
wrangler.toml

Environment Configuration

wrangler.toml

Local Development

For local testing:

Next Steps

Add rate limiting

Limit requests per key

Set usage limits

Cap total requests per key

Add permissions

Fine-grained access control

TypeScript SDK

Full SDK documentation

Troubleshooting

  • Ensure the key hasn’t expired or been revoked
  • Verify the Authorization header format: Bearer YOUR_KEY
  • Check that your root key is set correctly: wrangler secret list
  • Create a .dev.vars file in your project root
  • Add: UNKEY_ROOT_KEY=unkey_...
  • Never commit .dev.vars to version control
  • Ensure rate limits are configured on your API keys in the dashboard
  • Check that data.ratelimits is not empty in the verification response