Protecting Pages Using Clerk
Introduction
In this tutorial, we will learn how to protect specific routes in your Next.js application using Clerk. This ensures that certain pages are only accessible by authenticated users. You will learn how to set up Clerk's middleware to safeguard routes like dashboards or forums.
Prerequisites
Make sure you have already set up Clerk in your project. If you haven't done so, please refer to Clerk's official Next.js integration guide before proceeding.
Step 1: Define Protected Routes
First off, if you haven't done so already, create a new file in the root of your project called middleware.ts
. We'll begin by defining the routes that need protection using Clerk'sclerkMiddleware
and createRouteMatcher
. These routes will require authentication for users to access. This example is just the bare minimum to get you started. For more information on Clerk's middleware, check out their official docs: Clerk Docs.
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server"
// Specify the protected routes
const isProtectedRoute = createRouteMatcher(["/dashboard(.*)", "/forum(.*)"]);
// Apply the middleware for authentication
export default clerkMiddleware((auth, req) => {
if (isProtectedRoute(req)) {
auth().protect();
}
});
// Configuration to match routes, ignoring static files and Next.js internals
export const config = {
matcher: [
// Exclude Next.js internals and static assets
"/((?!_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)(.*)",
],
}
Step 2: Run the Project
Now that your routes are protected, let’s run the project and test it. You can use the following command to start your development server:
npm run dev
Once the server is running, try accessing a protected route such as/dashboard
or /forum
. If you are not logged in, you should be redirected to the sign-in page provided by Clerk.