next.jsmiddlewareclerk

Is it needed to check the signed-in status of a user when my middleware does it, using clerk?


I am building a simple app with NextJs and Clerk.
I set up the middleware to protect all routes but some.

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: [
    // 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)).*)',
    // Always run for API routes
    '/(api|trpc)(.*)',
  ],
};

After playing a bit with it, I was wondering: on my protected pages, do I need to check if the user is signed in ? (e.g. using useUser() hook)

Shouldn't it be check by the middleware ? Do I still need to check it in case that could be bypassed?

Many thanks to anyone willing to teach me a bit about this.

Matthieu


Solution

  • No, this isn't necessary. Once you protect a route in middleware you cannot bypass that since it runs on every request.

    In fact a scraper couldn't even know that a protected route exists without logging in unless you have a site map.

    Security digram of protected pages

    So yes you are good as long as Clerk behaves as it should.

    However, if your concern is with security checkout security and privacy from the Clerk team.