Skip to content

feat: enhance middleware to handle public and admin routes #44

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 31 additions & 5 deletions apps/web/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,38 @@
import { clerkMiddleware } from "@clerk/nextjs/server";
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";

export default clerkMiddleware();
const isAdminRoute = createRouteMatcher(["/admin(.*)"]);
const isPublicRoute = createRouteMatcher([
"/",
"/pricing(.*)",
]);

export default clerkMiddleware(async (auth, req) => {
// Handle public routes
if (isPublicRoute(req)) {
return NextResponse.next();
}

const userSession = await auth();

await auth.protect();

// Handle admin routes
if (isAdminRoute(req)) {
if (userSession?.sessionClaims?.metadata?.role !== "admin") {
const url = new URL("/", req.url);
return NextResponse.redirect(url);
}
}

return NextResponse.next();
});

export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
"/((?!_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)(.*)',
"/(api|trpc)(.*)",
],
};
};