Back to roadmaps clerk Course

Protecting Routes using Clerk Middleware

To protect route groups from unauthenticated visitors, create a middleware file that intercepts request paths before they reach page components.


1. Creating the Middleware File

Create a middleware.ts file in the root of your Next.js project (or inside the src/ folder if you use one):

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

// 1. Define public page matchers that do not require authentication
const isPublicRoute = createRouteMatcher([
  "/",
  "/sign-in(.*)",
  "/sign-up(.*)",
  "/blog(.*)",
]);

// 2. Intercept and evaluate requests
export default clerkMiddleware(async (auth, request) => {
  const authObject = await auth();
  
  if (!isPublicRoute(request)) {
    // If the route is private, force the user to sign in
    await authObject.protect();
  }
});

// 3. Configure matcher patterns that trigger the middleware execution
export const config = {
  matcher: [
    // Skip Next.js internals and static files
    "/((?!_next|[^?]*\\.(?:html|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
    // Always run for API routes
    "/(api|trpc)(.*)",
  ],
};

2. Setting Default Auth Paths

To ensure Clerk redirects users to the correct login routes, add these paths to your .env.local configuration:

NEXT_PUBLIC_CLERK_SIGN_IN_URL="/sign-in"
NEXT_PUBLIC_CLERK_SIGN_UP_URL="/sign-up"

If an unauthenticated user attempts to visit a protected route (such as /dashboard), the clerkMiddleware will redirect them to /sign-in.

Published on Last updated: