Clerk Integration
Secure Clerk authentication routes against VPNs, proxies, and Tor nodes via Next.js Edge Middleware.
An enterprise-grade, zero-dependency Next.js middleware wrapper that natively integrates ProxyTracer with Clerk . Protect your authentication routes from malicious traffic, credential stuffing, and unauthorized access by blocking VPNs, proxies, and Tor nodes without sacrificing Edge performance.
Features
- Minimal configuration required.
- Fully compatible with Vercel Edge, Cloudflare Workers, and self-hosted Nginx environments.
- Block high-risk traffic on sensitive routes (e.g.,
/sign-up) while explicitly permitting access to others. - Native Cloudflare CIDR validation prevents IP header spoofing and bypass attempts.
- Two-Tier Caching System: Built-in memory cache for burst traffic mitigation, with native support for global Redis integrations.
- Configurable Fallback: Enforce either Fail-Open (prioritize availability) or Fail-Closed (prioritize strict security) logic during API timeouts.
Installation
npm install proxytracer-clerk-middleware
# or
yarn add proxytracer-clerk-middleware
pnpm add proxytracer-clerk-middlewareImplementation Guide
Prerequisites
This package requires Next.js Edge Middleware. Ensure a middleware.ts (or .js) file exists at the root of your project or within your src/ directory.
Basic Usage
Integrate ProxyTracer with Clerk by wrapping clerkMiddleware(). By default, this enforces the security check across all routes matched by the Next.js middleware configuration.
import { clerkMiddleware } from "@clerk/nextjs/server";
import { withProxyTracer } from "proxytracer-clerk-middleware";
export default withProxyTracer(clerkMiddleware(), {
apiKey: process.env.PROXYTRACER_API_KEY || "", // Do not use NEXT_PUBLIC_ prefixes
});
export const config = {
matcher: [
// Exclude Next.js internals and all static files
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
// Always execute for API and tRPC routes
'/(api|trpc)(.*)',
],
};Advanced Configuration
For production environments, it is recommended to implement granular control over protected routes and configure specific infrastructure proxy settings.
1. Granular Route Policies
Apply specific actions per route to balance security and user access.
export default withProxyTracer(clerkMiddleware(), {
apiKey: process.env.PROXYTRACER_API_KEY || "",
// Define route-specific access policies
routeRules: [
{ path: "/sign-up", action: "block", fallbackUrl: "/vpn-warning" },
{ path: "/sign-in", action: "allow" }, // Explicitly allow proxies on this route
],
// Global fallback URL for unmatched blocked routes
fallbackUrl: "/access-denied"
});2. Infrastructure Native Support
Configure IP extraction based on your infrastructure provider to securely validate CIDR ranges and prevent header spoofing.
export default withProxyTracer(clerkMiddleware(), {
apiKey: process.env.PROXYTRACER_API_KEY || "",
trustedProxy: "vercel", // Use 'cloudflare' for Cloudflare, or 'vercel' for Vercel/Nginx
});3. Global Redis Caching (Optional)
ProxyTracer includes a 5-minute local memory cache for Edge isolates. To optimize API utilization across a distributed global architecture, provide a custom Redis adapter.
import { Redis } from '@upstash/redis';
const redis = Redis.fromEnv();
export default withProxyTracer(clerkMiddleware(), {
apiKey: process.env.PROXYTRACER_API_KEY || "",
cache: {
get: async (key) => await redis.get(key),
set: async (key, isProxy) => await redis.set(key, isProxy, { ex: 86400 }) // Cache globally for 24h
}
});API Reference
| Option | Type | Default | Description |
|---|---|---|---|
apiKey | string | Required | Your ProxyTracer API Key. |
trustedProxy | string | 'none' | Set to 'vercel' or 'cloudflare' to securely extract IP headers. |
routeRules | array | undefined | Array of objects defining granular { path, action, fallbackUrl }. |
routesToProtect | string[] | undefined | Legacy array of paths to block (e.g., ['/sign-up']). |
fallbackUrl | string | undefined | URL to redirect blocked users. Returns a 403 text response if omitted. |
failOpen | boolean | true | Dictates if the request is permitted upon API error or timeout. |
timeoutMs | number | 1000 | Maximum duration in milliseconds to wait for the API before aborting. |
extractIp | function | undefined | Escape hatch to execute custom IP extraction logic. |
Architecture & Security Considerations
To ensure optimal performance and cost-efficiency while utilizing Next.js Edge Middleware, please observe the following guidelines:
1. Next.js Route Matcher (Critical)
By default, Next.js executes middleware on every HTTP request. Failure to properly configure the matcher will result in unnecessary API invocations for static assets (e.g., .png, .css, _next/static). You must include the standard Next.js exclusion matcher at the bottom of your middleware.ts file to bypass static files, as demonstrated in the Basic Usage example.
2. Fail-Open vs. Fail-Closed Configurations
By default, the package is configured to failOpen: true. If the ProxyTracer API times out or network connectivity fails, the request is permitted to proceed. This prioritizes high availability and user experience.
For highly sensitive endpoints (e.g., financial transactions, identity verification), it is strongly advised to set failOpen: false. This ensures that a system failure results in a strict security lockdown.
3. Edge Node Caching Limitations
The built-in memory cache retains IP classification data for 5 minutes per Edge isolate. Because platforms like Vercel and Cloudflare distribute requests across hundreds of isolated nodes globally, this cache operates strictly locally per node. It provides effective burst protection but does not synchronize state globally. To minimize API usage and enforce true 24-hour global caching, a Redis database integration is required.
Security Guidelines
- Make sure your ProxyTracer API key doesn’t start with
NEXT_PUBLIC_. If it does, the middleware will throw an error and crash on startup to save you from accidentally leaking it to the browser. - If you are deploying with, say, an Nginx reverse proxy, you need to configure Nginx to pass the
X-Real-IPorX-Forwarded-Forheaders. Once that is done, just settrustedProxy: "vercel"in the middleware options so it knows how to read them properly.
License
This software is licensed under the GNU Affero General Public License v3.0 (AGPLv3). See the LICENSE file for full details.