Skip to main content

Overview

This guide covers everything you need to protect your Express.js API with Unkey, including basic setup, reusable middleware, permission checks, and production-ready patterns. What you’ll learn:
  • Quick setup with the Unkey SDK
  • Reusable middleware patterns
  • Permission-based access control
  • Rate limiting integration
  • Error handling best practices

Prerequisites

Quick Start

1

Create your Express app

2

Add your root key

Get a root key from Settings → Root Keys and create a .env file:
.env
Never commit your .env file. Add it to .gitignore.
3

Create your server

Create index.js with a protected route:
index.js
4

Start your server

5

Test it

First, create a test key in your Unkey dashboard, then:
Test with valid key
You should see:

Reusable Middleware

For cleaner code, extract verification into middleware:
middleware/auth.js
Use it on any route:

TypeScript Version

For TypeScript projects:
middleware/auth.ts

Rate Limit Headers

Include rate limit info in response headers:
middleware/auth.ts

Permission-Based Access

Create middleware that requires specific permissions:
middleware/permissions.ts
Use it:

Protect Entire Router

Apply middleware to an entire router:
app.ts

Verification Response Data

After successful verification, data contains:

Next Steps

Add rate limiting

Limit requests per key

Set usage limits

Cap total requests per key

Add permissions

Fine-grained access control

SDK Reference

Full TypeScript SDK docs

Troubleshooting

  • Ensure the key hasn’t expired or been revoked
  • Verify the Authorization header format: Bearer YOUR_KEY (note the space)
  • Check that your root key has the verify_key permission
  • Check that UNKEY_ROOT_KEY is set correctly in your .env
  • Make sure you’re calling require("dotenv").config() before using env vars
  • Check the Unkey dashboard for any service issues