Route protection and authorization patterns for Clerk middleware. Use when implementing route guards, protecting API routes, configuring middleware matchers, setting up role-based access control, creating auth boundaries, or when user mentions middleware, route protection, auth guards, protected routes, public routes, matcher patterns, or authorization middleware.
View on GitHubFebruary 1, 2026
Select agents to install to:
npx add-skill https://github.com/vanman2024/ai-dev-marketplace/blob/main/plugins/clerk/skills/middleware-protection/SKILL.md -a claude-code --skill middleware-protectionInstallation paths:
.claude/skills/middleware-protection/# Middleware Protection Comprehensive route protection and authorization patterns for Clerk middleware in Next.js applications. Provides middleware configuration, route matchers, role-based access control, and authentication boundaries. ## Core Concepts ### Middleware Architecture - **Edge Runtime**: Clerk middleware runs on Cloudflare Workers/Vercel Edge - **Request Interception**: Middleware executes before route handlers - **Auth State**: Access to authentication state via `auth()` helper - **Matcher Patterns**: Configure which routes middleware applies to ### Route Protection Levels 1. **Public Routes**: Accessible without authentication (sign-in, sign-up, landing pages) 2. **Protected Routes**: Require authentication (dashboards, user profiles) 3. **Organization Routes**: Require organization membership 4. **Role-Based Routes**: Require specific roles or permissions ### Security Principles - **Deny by Default**: All routes protected unless explicitly made public - **Defense in Depth**: Middleware + server component checks + API route guards - **Session Validation**: Automatic token validation on every request - **CSRF Protection**: Built-in protection against cross-site request forgery ## Instructions ### Basic Middleware Setup 1. **Create middleware.ts in project root** - Import `clerkMiddleware` from `@clerk/nextjs/server` - Export default middleware function - Configure matcher for routes to protect 2. **Configure Public Routes** - Define routes accessible without authentication - Use glob patterns for route matching - Include sign-in/sign-up pages as public 3. **Set Protected Routes** - Specify which routes require authentication - Use route groups for organization - Apply different protection levels ### Advanced Patterns 1. **Role-Based Access Control** - Check user roles in middleware - Redirect based on permissions - Implement organization-level permissions 2. **Conditional Route Protection** - Apply di