How do I configure my middleware such that it can check for authenticated users, if they are authenticated then all pages are available to them, otherwise only /login is available to them and they are redirected to /login?
//import { updateSession } from './lib';
export async function middleware(request: NextRequest) {
const session = request.cookies.get('session');
if (session && request.nextUrl.pathname.startsWith("/login")) {
const dashboardUrl = new URL('/', request.url);
return NextResponse.redirect(dashboardUrl);
}
// Check if it's a request to the login page or if the session exists
if (request.nextUrl.pathname.startsWith("/login") || session) {
return NextResponse.next();
}
// Redirect to login page if no session and not already heading to /login
const loginUrl = new URL('/login', request.url);
return NextResponse.redirect(loginUrl);
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$|/login).*)'],
};
this is my middleware now but I am having errors and I am also able to access all pages without authorisation.