[Nextauth] How to use middleware with grouped routes?

I have an application where admin pages are in a grouped route /app/(admin)/dashboard rather than /app/admin/dashboard. Is there a way for the nextauth middleware matcher to protect grouped routes?
5 Replies
Furki4_4
Furki4_413mo ago
Securing pages and API routes | NextAuth.js
You can easily protect client and server side rendered pages and API routes with NextAuth.js.
Furki4_4
Furki4_413mo ago
see the green TIP part, I believe that's what you want
Trader Launchpad
Trader LaunchpadOP13mo ago
Hey thank you for the reply. This is how I currently have it setup, with all admin routes under app/admin/dashboard so they render https://.../admin/dashboard but if i want to use a grouped route so they render https://.../dashboard with them in a nextjs grouped route app/(admin)/dashboard, i cant figure out how to correctly use the matcher. /(admin)/:path* does not work
Furki4_4
Furki4_413mo ago
hmm monkaHmm you can call getServerSession function to get the session in the server side and guard your pages under this layout by redirecting based on session. I guess this might work because when you go to a page that's grouped under (admin) folder, the layout.tsx will be triggered and you can manage the redirection here. I don't know if you can handle route guard using route groups because they don't have any effect on URL. So, you might not be able to set a matcher. May I ask why you don't use /admin/:path ? You can use layout file in admin folder if that's what you need.
Trader Launchpad
Trader LaunchpadOP13mo ago
That is what I am using now. I dont personally care that much, just could not find any info on next auth protecting a core functionality of new nextjs, which is route groups. seemed like with all the hooplah over app router nextauth would have implemented it in their middleware. I think i remember somewhere that you could use regex in the matcher. Again not sure if the regex would even pick up on the route group from the url to parse. Its middleware and i suppose doesnt have access to what route groups nextjs has.
Want results from more Discord servers?
Add your server