Search code examples
reactjsnode.js

Why it doesn't redirect to the login page if the user is not logged in?


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" });
  }
});

Solution

    1. You don't trigger the redirect inside the catch block.
    2. If an error occurs (such as an unauthorized request), the navigate("/login") inside the if (response.status !== 201) condition won't execute because an exception will already be thrown.
    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
      }
    };