Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught SyntaxError: expected expression, got '<' while using Next.js middleware

I'm using Next.js middleware to redirect to the login page if there's no available token using Spotify's API,

My middleware looks like this:

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

export async function middleware(req: NextRequest) {
  //   const token = await getToken({ req, secret: process.env.JWT_SECRET });
  const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
  const { pathname, origin } = req.nextUrl;
  if (pathname.includes("/api/auth") || token) {
    return NextResponse.next();
  }
  //   console.log(origin);
  // console.log(token);

  if (!token && pathname != "/login") {
    return NextResponse.redirect(new URL(`${origin}/login`));
  }
}

If I comment out this section:

  if (!token && pathname != "/login") {
    return NextResponse.redirect(`${origin}/login`);
  }

I stop getting the error but obviously, I need this line to redirect if there's no token, I tried to check for any syntax errors or any mistakes but I can't seem to find it myself, any help?

the errors i'm getting are these :

Uncaught SyntaxError: expected expression, got '<'
react-refresh.js:1
Uncaught SyntaxError: expected expression, got '<'
webpack.js:1
Uncaught SyntaxError: expected expression, got '<'
main.js:1
Uncaught SyntaxError: expected expression, got '<'
_app.js:1
Uncaught SyntaxError: expected expression, got '<'
login.js:1
Uncaught SyntaxError: expected expression, got '<'
_buildManifest.js:1
Uncaught SyntaxError: expected expression, got '<'
like image 671
Mohamed Nabil Avatar asked Dec 11 '25 02:12

Mohamed Nabil


2 Answers

the problem is Next.js is making some request to /_next/* and you redirect request to the login page, those requests are needed and but are never finished.

You need to avoid redirect any requests made to /_next/*

export const config = {
  matcher: [
    '/((?!_next|api/auth).*)(.+)'
  ],
}
like image 93
Rongeegee Avatar answered Dec 12 '25 14:12

Rongeegee


I had the same issue, the solution that worked for me was

export const config = {
matcher: "/",
};

Add this code to your middleware.ts file and this would solve the issue :)

like image 22
Jashandeep Singh Avatar answered Dec 12 '25 14:12

Jashandeep Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!