Uncaught SyntaxError: Unexpected token '<' when using Next Middleware
Asked Answered
C

2

7

I have a simple middleware setup that checks if the user is logged in using a boolean from the zustand store, and redirect the user to the login page accordingly. This was as per the docs

   import { NextResponse } from "next/server";
    import type { NextRequest } from "next/server";
    import { useAuthStore } from "./zustand/store";
    
    export function middleware(request: NextRequest) {
      const loggedIn = useAuthStore.getState().loggedIn;
      if (!loggedIn) {
        const url = request.nextUrl.clone();
        url.pathname = "/login";
        return NextResponse.rewrite(url);
      } else {
        return NextResponse.rewrite(request.nextUrl.clone());
      }
    }

When i use this middleware however, I get

react-refresh.js?ts=1661359264454:1 Uncaught SyntaxError: Unexpected token '<' (at react-refresh.js?ts=1661359264454:1:1)
18:41:04.842 webpack.js?ts=1661359264454:1 Uncaught SyntaxError: Unexpected token '<' (at webpack.js?ts=1661359264454:1:1)
18:41:04.842 main.js?ts=1661359264454:1 Uncaught SyntaxError: Unexpected token '<' (at main.js?ts=1661359264454:1:1)
18:41:04.909 _app.js?ts=1661359264454:1 Uncaught SyntaxError: Unexpected token '<' (at _app.js?ts=1661359264454:1:1)
18:41:04.924 index.js?ts=1661359264454:1 Uncaught SyntaxError: Unexpected token '<' (at index.js?ts=1661359264454:1:1)
18:41:04.925 _buildManifest.js?ts=1661359264454:1 Uncaught SyntaxError: Unexpected token '<' (at _buildManifest.js?ts=1661359264454:1:1)
18:41:04.925 _ssgManifest.js?ts=1661359264454:1 Uncaught SyntaxError: Unexpected token '<' (at _ssgManifest.js?ts=1661359264454:1:1)
Cavalierly answered 24/8, 2022 at 16:53 Comment(3)
Does this answer your question: Uncaught SyntaxError: expected expression, got '<' while using Next.js middleware?Beka
Question has already been asked and answered, see comment above by juliomalvesCondemnation
Does this answer your question? Uncaught SyntaxError: expected expression, got '<' while using Next.js middlewareEvonneevonymus
S
2

In my case, I applied middleware by blacklist, like this.

export const config = {
  matcher: ["/((?!login|signup).*)"],
}

By writing this, the middleware applied to unintended requests and cause the confusing error. By fixing to whitelist matcher, the error resolved.

export const config = {
  matcher: ["/", "/settings", ....],
}
Susannahsusanne answered 29/11, 2023 at 13:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.