Fix Stripe Webhook 401 with Clerk Middleware

Clerk middleware protects all routes by default. Stripe is not an authenticated user — it has no Clerk session. The middleware returns 401 before your webhook handler ever runs.

Why it's hard to debug: The 401 comes from Clerk's middleware, not your code. Your webhook handler logs show nothing. Stripe retries silently. You see failed deliveries in the Stripe dashboard with no corresponding server logs.

The fix — exclude /api/webhooks from Clerk

// middleware.ts
import { clerkMiddleware } from '@clerk/nextjs/server';

export default clerkMiddleware();

export const config = {
  matcher: [
    // Exclude webhook routes from Clerk auth
    '/((?!api/webhooks|_next/static|_next/image|favicon.ico).*)',
    '/(api|trpc)(.*)',
  ],
};

Verify the fix works

# After deploying, send a test request without a Stripe signature
# If Clerk is no longer blocking, you'll get 400 (missing signature) not 401
curl -X POST https://yoursite.com/api/webhooks/stripe   -H "Content-Type: application/json"   -d '{}'

# Expected: 400 Bad Request (missing stripe-signature)
# Was getting: 401 Unauthorized

Using clerkMiddleware with auth logic?

If you need to protect some API routes while keeping webhooks open, use the callback form:

// middleware.ts
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server';

const isProtectedRoute = createRouteMatcher(['/api/protected(.*)']);

export default clerkMiddleware((auth, req) => {
  if (isProtectedRoute(req)) auth().protect();
  // Webhook routes are not matched — they pass through
});

export const config = {
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};

NextAuth / Better Auth same fix

// middleware.ts — NextAuth
export { default } from 'next-auth/middleware';
export const config = {
  matcher: ['/((?!api/webhooks|_next|[^?]*\.(?:html?|css|js)).*)', '/(api|trpc)(.*)'],
};

Generate the complete Stripe + Clerk handler with middleware exclusion.

Open WebhookFix →
For informational purposes only. Always test in staging before production. MetricLogic accepts no responsibility for issues arising from use of these tools. © 2026 MetricLogic.
HttpFixer by MetricLogic · Blog · All Tools · Generators MIT · GitHub →