this is my middleware
import { NextResponse } from "next/server";
export async function middleware(request: Request) {
const authUrl = "http://localhost:5000/api/auth/checkAuth";
try {
const res = await fetch(authUrl);
const data = await res.json();
console.log(data);
if (data.exists === true) {
console.log(data.exists);
return NextResponse.next();
}
return NextResponse.redirect(new URL("/login", request.url));
} catch (err) {
console.log(err);
return new NextResponse("Internal Server Error", { status: 500 });
}
}
export const config = {
matcher: ["/"],
};
and this is my route in my express server
export const checkAuth = async (req, res) => {
console.log(req.session.userId);
if (!req.session.userId) {
return res.status(400).json({ error: "You are not logged in" });
}
try {
const user = await User.findById(req.session.userId);
if (user) {
return res.json({ exists: true, user });
} else {
return res.json({ exists: false });
}
} catch (err) {
return res
.status(500)
.json({ error: "An error occurred while checking the user" });
}
};