The middleware.ts (or proxy.ts in this context) uses Clerk's clerkMiddleware to intercept requests and enforce authentication. You can define protected routes using createRouteMatcher with an array of path patterns. If a request matches a protected route, auth.protect() is called to ensure the user is authenticated; otherwise, the request proceeds normally.
To ensure the middleware runs on the correct routes, export a config object with a matcher array. The provided pattern is a standard Next.js middleware matcher that excludes static assets and internal Next.js files while including API and TRPC routes.
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
// Define which routes require authentication
const isProtectedRoute = createRouteMatcher(["/notes(.*)"]);
export default clerkMiddleware(async (auth, request) => {
// If the route is not protected, do nothing
if (!isProtectedRoute(request)) return;
// Enforce authentication for protected routes
await auth.protect();
});
// Configure the middleware matcher
export const config = {
matcher: [
"/((?!_next|[^?]*\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
"/(api|trpc)(.*)",
],
};