import { NextResponse, NextRequest } from "next/server";
import { getToken } from "next-auth/jwt";
export async function middleware(request: NextRequest) {
const session = await getToken({ req: request, secret: process.env.SECRET });
const pathName = request.nextUrl.pathname; // Get pathname of the current request
// Check if a session exists and if the request path is '/login'
if (session && pathName === "/login") {
// If yes, clone the URL and change its pathname to the home page
const url = request.nextUrl.clone();
url.pathname = "/";
return NextResponse.redirect(url);
// Check if user not logged in, and on the main page
}
if (!session && pathName !== "/login") {
// If yes, clone the URL and change its pathname to the login page
const url = request.nextUrl.clone();
url.pathname = "/login";
return NextResponse.redirect(url);
}
// Continue processing the request if the conditions are not met
return NextResponse.next();
}
when i do if (!session && pathName !== "/login") than i have an errors:
Uncaught SyntaxError: Unexpected token '<' (at webpack.js?v=1710935355737:1:1)
Uncaught SyntaxError: Unexpected token '<' (at main-app.js?v=1710935355737:1:1)
Uncaught SyntaxError: Unexpected token '<' (at app-pages-internals.js:1:1)
Uncaught SyntaxError: Unexpected token '<' (at page.js:1:1)
Uncaught SyntaxError: Unexpected token '<' (at layout.js:1:1)
Manifest: Line: 1, column: 1, Syntax error.
If i write if (!session && pathName === "/") Everything works as it should, but I have a dynamic id and I can't do the same check for all of the pages
I tried googling, I couldn't find anything. I expect that when the user clicked on the "Logout" button on any page in the application, it redirected to the "Login" page, it even redirects and shows the login button
"use client";
import { signIn } from "next-auth/react";
function Login() {
return (
<main>
<button onClick={() => signIn("azure-ad", { callbackUrl: "/" })}>
Login with Microsoft
</button>
</main>
);
}
export default Login;
but I get the errors described above, and button don't work