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)
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", ....],
}
Answered by Uncaught SyntaxError: expected expression, got '<' while using Next.js middleware
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With