Next.js Discord

Discord Forum

how do i add an entire route group to public routes in the middleware file

Unanswered
American Kestrel posted this in #help-forum
Open in Discord
American KestrelOP
how do i add an entire route group to public routes in the middleware file?

15 Replies

Asian black bear
Set up a middleware function which checks for public routes. You can define an array of public groups than that you want to be in the public routes, then check to see if the current route is in that array that you defined.

import { NextApiRequest, NextApiResponse } from 'next'; import { useRouter } from 'next/router'; export const checkPublicRoute = (handler) => (req, res) => { const router = useRouter(); const publicRoutes = ['/public-route-1', '/public-route-2']; if (publicRoutes.includes(router.pathname)) { // This route is public, so you can handle it accordingly return handler(req, res); } res.status(403).json({ error: 'Access denied. Please log in.' }); };

If I have misunderstood what you are asking, please let me know
American KestrelOP
Hi, actually
I have 2 route groups
I want all the pages in that route group
to be public
lets call one group1, and the other group2
like this
const publicRoutes = ['/public-route-1', '/public-route-2'];
could you please tell me how i can rewrite this line for my usecase
here's my middleware.ts file
import { authMiddleware } from "@clerk/nextjs"; export default authMiddleware({ publicRoutes: ['/', '/api/webhooks/user/route', '/api/webhooks/user', '/api/webhooks/stripe', /^\/share\/.+/], }); export const config = { matcher: ["/((?!.*\\..*|_next).*)", "/", "/(api|trpc)(.*)"], };
American KestrelOP
are you saying i should individually add all the pages in a route group
is that the way to go
@American Kestrel are you saying i should individually add all the pages in a route group
Asian black bear
So in your case (general) and (user-specific) have no baring on the url, so if we are trying to match urls you need to go to the folder structure inside of these. For example if you had a profile route '/profile' and this had lots of sub folders or nested routes. Then you could match the middleware to find everything inside of the profile route like /profile/posts or /profile/bio

To be more clear to if you had a profile folder inside of the general and you tried matching the profile url, the middleware would not know which folder it should be looking at as your trying to match the path of /profile