I am implementing protected routes and the code successfully generates the status 500 server error if the user is not logged in. now I want to redirect a user to the login page if the user is not logged. I tried using this code but it doesn't seems to be working. what is the error here?
This is the code that handles redirecting in the frontend
const fetchUser = async () => {
try {
const token = localStorage.getItem("token");
const response = await axios.get("http://localhost:3001/auth/home", {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.status !== 201) {
navigate("/login");
}
} catch (err) {
console.log(err);
}
};
This is the code that checks the token in the backend
const verifyToken = async (req, res, next) => {
try {
const token = req.headers["authorization"].split(" ")[1];
if (!token) {
return res.status(403).json({ message: "no token available" });
}
const decodedPayload = jwt.verify(token, process.env.JWT_KEY);
req.username = decodedPayload.username;
next();
} catch (err) {
return res.status(500).json({ message: "server error" });
}
};
router.get("/home", verifyToken, async (req, res) => {
try {
console.log(req.username);
if (req.username !== "admin") {
return res.status(404).json({ message: "invalid username" });
}
return res.status(201).json({ message: "user has logged in" });
} catch (err) {
return res.status(500).json({ message: "server error" });
}
});
const fetchUser = async () => {
try {
const token = localStorage.getItem("token");
const response = await axios.get("http://localhost:3001/auth/home", {
headers: {
Authorization: `Bearer ${token}`,
},
});
if (response.status !== 201) {
navigate("/login"); // This might never be reached if an error is thrown
}
} catch (err) {
console.error("Authentication error:", err);
navigate("/login"); // Redirect
}
};