Building an API Key Generator with Upstash Redis
API keys are like the front-door keys to your service—they let users in while keeping things secure. In this blog, I’ll walk you through building a simple, secure API key generator using Upstash Redis for fast, serverless data storage and Cloudflare Workers to handle requests at the edge. Whether you’re setting up a new service or adding keys to an existing app, you’ll learn how to generate, store, and validate API keys to keep everything running smoothly and efficiently.
What is an API Key?
An API key is a unique code that identifies and authenticates a user or application trying to access your API. Think of it like a personal pass: when someone wants to use your service, they need to show this “key” to prove they’re allowed in. API keys help you control who can access your resources, and they’re often used to track usage, enforce limits, or prevent unauthorized access. They’re a straightforward way to manage API access and keep your data secure.
What We'll Build
In this guide, we’ll create an api key generator that provides two core functionalities:
- Generating new API keys with custom settings
- Validating API keys while retrieving their metadata
Key features will include:
- Customizable key prefixes
- Expiration dates
- Rate limiting
- Metadata storage
- Owner identification
Let's visualize our API key system
This diagram illustrates the interaction between the client, our Cloudflare Worker, and Upstash Redis for both creating and validating API keys. With this overview in mind, let's start building our system.
Prerequisites
To follow along, you’ll need:
- A Cloudflare Workers account
- An Upstash account
- Node.js installed on your local machine
Project Structure
Our project will have the following structure:
folder-name/
├── src/
│ ├── config/
│ │ ├── generateApiKey.ts
│ │ └── schema-validation.ts
│ ├── lib/
│ │ └── ratelimit.ts
│ ├── routes/
│ │ ├── create.ts
│ │ └── verify.ts
│ ├── types/
│ │ └── api.ts
│ └── index.ts
├── package.json
└── wrangler.toml
Step 1: Project Setup
Let's start by setting up our project and installing the necessary dependencies.
Create a new project directory
Open your terminal and run the following commands:
Install dependencies
We'll need a few packages for our project:
@upstash/redis
: Upstash Redis client for serverless environments
@upstash/ratelimit
: Rate limiting library for Upstash Redis
@hono/zod-validator
: Request validation middleware for Hono
zod
: TypeScript-first schema validation library
wrangler
: Cloudflare's CLI for Workers development and deployment
Set up Upstash Redis
- Log in to your Upstash account and create a new Redis database
- Once created, navigate to the "REST API" section
- Copy the
UPSTASH_REDIS_REST_URL
andUPSTASH_REDIS_REST_TOKEN
in the.env
section
Configure Cloudflare Workers
Create a wrangler.toml
file in your project root with the following content:
Replace "your-redis-url"
and "your-redis-token"
with the values you copied from Upstash.
Step 2: Defining API Types
Let's start by defining our TypeScript interfaces for our API requests and responses. These types will help us maintain type safety throughout our application. Create a new file src/types/api.ts
:
Step 3: Implementing API Key Generation
Now, let's create a utility function to generate our API keys. Create a new file src/config/generateApiKey.ts
:
This function generates a random API key using cryptographically secure random bytes, encodes it in base64, and makes it URL-safe.
Step 4: Implement Rate Limiting
Create a file src/lib/ratelimit.ts
:
Step 5: Creating the API Routes
Let's set up our main application file and create our API routes. This file sets up our Hono application with two main routes: /keys/create
for generating new API keys and /keys/verify
for validating existing keys with three separate files.
1. Implement Create API Key Route
Create a file src/routes/create.ts
:
2. Implement Verify API Key Route
Create a file src/routes/verify.ts
:
3. Implement the Main file index.ts
implement the main file src/index.ts
to import create.ts
, verify.ts
, and rateLimitMiddleWare
Step 6: Deployment
Deploy your Keyflow application to Cloudflare Workers:
-
Install Wrangler:
-
Authenticate with Cloudflare:
-
Deploy your worker:
Step 7: Deployment
Now that we have our application ready, let's deploy it to Cloudflare Workers:
-
Make sure you have the Wrangler CLI installed:
npm install -g wrangler
-
Authenticate with your Cloudflare account:
wrangler login
-
Deploy your worker:
wrangler deploy
Step 8: Testing Your API
Let's test our newly deployed API:
Creating a New API Key
curl -X POST https://keyflow.<your-subdomain>.workers.dev/keys/create \
-H "Content-Type: application/json" \
-d '{
"apiId": "my-api",
"prefix": "prod",
"name": "Production API Key",
"expires": 1735689600000,
"meta": {
"environment": "production",
"team": "backend"
}
}'
Verifying an API Key
curl -X POST https://keyflow.<your-subdomain>.workers.dev/keys/verify \
-H "Content-Type: application/json" \
-d '{
"key": "prod_AbC123XyZ..."
}'
Replace <your-subdomain>
with your Cloudflare Workers subdomain and prod_AbC123XyZ...
with an actual key generated from the create endpoint.
Conclusion
Creating an API key generator is a key step in securing your application's APIs and managing who can access your services. By building a system that can generate, validate, and manage API keys, you add a strong layer of access control that helps keep your data safe and organized.
Here’s a quick rundown of what goes into a solid API key generator:
- Secure Key Generation: Unique, secure keys that include options like custom prefixes or set lengths make each key distinct and harder to guess.
- Validation and Expiration: Adding checks and expiration dates ensures each key is valid only for a set time, making it easy to control and limit access as needed.
- Metadata and Rate Limits: Storing extra information with each key and setting rate limits lets you monitor key usage, track activity, and avoid any abuse of your API.
Using tools like Upstash Redis and Cloudflare Workers makes it easy to build a serverless and globally distributed key management system that scales well and works efficiently.
With this foundation, you’re set up to keep access to your APIs secure and manageable, giving you peace of mind that your resources are protected and easy to monitor.