Reputation: 93
// new Clerk Auth
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
const isPublicRoute = createRouteMatcher(["/sign-in", "/sign-up"]);
export default clerkMiddleware((auth, request) => {
// publicRoutes: ["/api/:path*"];
if (!isPublicRoute(request)) {
auth().protect();
}
});
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};
// Old Clerk
import { authMiddleware } from "@clerk/nextjs"
export default authMiddleware({
publicRoutes: ["/api/:path*"],
});
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};
I am building a NextJS app using the Clerk Authentication, and I am having a big problem with the new Clerk, which is complex than the previous version. I am trying to protect all my routes, but make the "/api" routes public so that I can fetch the data from the server side. With the old version, it was very easy because with the authMiddleware, all routes were protected by default, and all you had to do was to make some public with the isPublicRoute, but with the new version, the clerkMiddleware does not protect any route by default and the isPublicRoute is no longer suported, so, doing the protecting and making other routes public at the same time is kinda painful for me. I read their documentation, but it is very hard to set up
Upvotes: 1
Views: 2129
Reputation: 21
The new Clerk update provides the desired behaviour of protecting no routes by default as requested by many developers. However, replicating the previous behaviour can easily be achieved by inverting the matcher condition in your middleware.ts
file:
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'
const isPublicRoute = createRouteMatcher(['/sign-in(.*)', '/sign-up(.*)']);
export default clerkMiddleware((auth, request) => {
if(!isPublicRoute(request)) {
auth().protect();
}
});
export const config = {
matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
}
Using the above config, all routes are protected by default except for the /sign-in
and /sign-up
routes. The code example is provided in the docs here.
Upvotes: 2