Next.js Discord

Discord Forum

Redirect to `not found` if route doesn't exist

Unanswered
Tan posted this in #help-forum
Open in Discord
TanOP
Hey friends. I have a public route which is / and I have a protected route which is dashboard but I will have more routes that I want to protect. I have a middleware where I specify the publicRoutes: [...] and I tried using the matcher to protect everything that is not specified in the publicRoutes which works fine it's just It will protect all routes even if they don't exist if that makes sense. My matcher looks like this: matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],

I am thinking at two ways to approach this:

1. Define all routes something like /app/:path* so that means everything starts with /app is protected
2. Check (somehow) if route exists and only if it does apply the middleware to check if the route is protected or protect all routes that exist except the one in publicRoutes.

ps. I use Clerk for auth.

I hope this makes sense. Not need to mention I'm new to React / Next.js 🙂

Thanks.

3 Replies

TanOP
Yeah I know. I actually have that page open. It's just using the matcher in their example will protect all routes even if the route doesn't exist.
TanOP
Thoughts ?