3

I`m trying to redirect a user to specific pages based on role, using the following code in the middleware.ts file

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { getToken } from 'next-auth/jwt'

export async function middleware(request: NextRequest) {
    const token = await getToken({
        req: request,
        secret: process.env.JWT_SECRET
    }) as any
    if (token !== null && token.user.role === "admin") {
        if (request.nextUrl.pathname.startsWith('/admin')) {
            return NextResponse.next()
        }
        else {
            return NextResponse.redirect(new URL('/admin', request.url))
        }
    }
}
/* export const config = {
    matcher: [
     //   "/login",
     //  "/register",
     //  "/",
     //   "/admin"
    ],
} */

From what I understood from the docs it will run for all the routes, but I get this error :

Uncaught SyntaxError: Unexpected token '<

enter image description here

However, if I include the matcher in the middleware file, it works as intended:

export const config = {
    matcher: [
       "/login",
       "/register",
       "/",
       "/admin"
    ],
}

Is there a fix for that error? Or just add all the pages to the matcher array?

0

1 Answer 1

1

When they say a middleware without a matcher runs for every request, it includes requests for getting everything, including favicons, JavaScript files, CSS files... as you can read on the doc.

You, in your if statement, you are saying, anything that does not start with '/admin", should be redirected to '/admin". So when the browser asks for those JavaScript files, you are redirecting it, which results in an HTML file being sent. This is the problem.

With the matcher, you are not blocking the browser from accessing the files that are needed to build the page, and scoping the middleware only on these paths:

export const config = {
  matcher: ["/login", "/register", "/", "/admin"],
};
Sign up to request clarification or add additional context in comments.

1 Comment

thank you , i got the reason now behind the error , adding '/((?!api|_next/static|_next/image|favicon.ico).*)' to the matcher fixed it like from the docs .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.