FRAMEWORK Edge Runtime (Vercel Edge, Cloudflare)

API Key Authentication for Next.js

Edge-compatible middleware that protects your API routes with sub-50ms verification, AI token budgets, and automatic rate limiting. Built for GPT wrappers and AI-first apps.

How do I add API key auth to Next.js?

Install @holdify/nextjs, add middleware.ts with createHoldifyMiddleware(), and configure the matcher for /api/*. Keys verify in <50ms at the edge with automatic rate limiting. Token budgets and dollar limits supported for AI apps.

npm install @holdify/nextjs
Next.js Integration
typescript
// middleware.ts
import { createHoldifyMiddleware } from '@holdify/nextjs';

const holdify = createHoldifyMiddleware({
  apiKey: process.env.HOLDIFY_PROJECT_KEY!,
});

export async function middleware(request: NextRequest) {
  // Protect all /api routes
  if (request.nextUrl.pathname.startsWith('/api')) {
    return holdify(request);
  }
}

export const config = {
  matcher: '/api/:path*'
};

Why Holdify for Next.js

AI Token Budgets

Cap GPT-4/Claude tokens per customer. Set dollar limits to protect margins from runaway AI costs.

Edge Runtime Compatible

Works on Vercel Edge Functions and Cloudflare Pages. Zero cold starts, global distribution.

App Router Native

First-class support for Next.js 13+ App Router with middleware integration.

Type-Safe

Full TypeScript support with typed verification results and entitlements.

Features

Middleware Integration

Drop-in middleware for Next.js that protects all /api routes automatically.

Route-Specific Protection

Configure which routes require API keys with matcher patterns.

Automatic Headers

Sets X-RateLimit-* headers automatically on responses.

Request Context

Access verification results in route handlers via getHoldifyResult().

Frequently Asked Questions

Can Holdify limit AI tokens per customer?

Yes. Set token budgets (e.g., 100K GPT-4 tokens/month) or dollar limits ($50/month). Holdify tracks usage and enforces limits automatically.

Does @holdify/nextjs work with Edge Runtime?

Yes. The SDK is fully compatible with Next.js Edge Runtime and works on Vercel Edge Functions and Cloudflare Pages.

Can I use it with Pages Router?

Yes. While examples show App Router, the middleware works with both Pages Router and App Router.

What's the latency overhead?

Typically 20-50ms depending on location. Holdify uses edge infrastructure to minimize latency globally.

Start Protecting Your Next.js API

Get started in under 10 minutes. Free tier includes 150K requests/month.

Get Started with Next.js