I’m working on a Next.js project where I have two route groups, (auth) which contains my auth pages and (root) which contains the dashbaord and other pages and a homepage “/. I have a middleware function that redirects requests to the sign-in path found in the (auth) route group “(auth)/sign-in”
import { cookies } from 'next/headers';
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
const cookieStore = cookies()
const accessToken = cookieStore.get('accessToken');
if (!accessToken && request.nextUrl.pathname !== '/') {
return NextResponse.redirect(new URL('/sign-in', request.url))
}
}
export const config = {
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - auth (authentication routes)
* - _next/static (static files)
* - _next/image (image optimization files)
* - *.png (PNG image files)
*/
matcher: ["/((?!api|auth|_next/static|_next/image|.*\.png$).*)"],
}
Here is my project structure
src
│
├── app/
│ ├── (auth)/
│ │ ├── sign-in
│ │ | ├── page.tsx
│ │ ├── layout.tsx
│ │
│ ├── (root)/
│ │ ├── dashboard/
| | | ├── page.tsx
│ | ├── layout.tsx
| |
│ ├── page.tsx
│ ├── layout.tsx
│ └── ...
│
├── middleware.tsx
│
└── ...
How can I modify this middleware to handle both the (auth) and (root) route groups effectively?
I tried using regex as above but it doesn't work for other routes inside the (root) group
Any help or insights would be greatly appreciated. Thanks in advance!
I tried using regex as above but it doesn't work for other routes inside the (root) group
New contributor
Kano Dekou Billy Brown is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.