Expected: the async function checks if the user is authenticated, then return true, so that the protected component gets rendered, or false, that redirects the user to the login page.
What actually happens:
the getAuth() function returns "Promise ", breaking the code.
export default function RequireAuth({ children, redirectTo }) {
const BASE_API_URL = "https://api-backend.test";
const getAuth = async () => {
const isAuth = await axios
.get(BASE_API_URL + "/user_auth.php", {
withCredentials: true,
})
.then((res) => {
if (res.status === 201) {
return true;
}
})
.catch((err) => {
if (err.response.status === 401) {
return false;
}
});
return isAuth;
};
let isAuthenticated = getAuth();
return isAuthenticated ? children : <Navigate to={redirectTo} />;
}
This is how the "protected" component should be displayed according to the official documentation here.
<Route
path="/dashboard"
element={
<RequireAuth redirectTo="/login">
<Dashboard />
</RequireAuth>
}
/>
You have to do it properly using useEffect, try this
export default function RequireAuth({ children, redirectTo }) {
const BASE_API_URL = "https://api-backend.test";
const [isAuthenticated, setAuthenticated] = useState(false);
useEffect(() => {
const getAuth = () => {
const isAuth = axios
.get(BASE_API_URL + "/user_auth.php", {
withCredentials: true
})
.then((res) => {
if (res.status === 201) {
setAuthenticated(true);
}
})
.catch((err) => {
if (err.response.status === 401) {
setAuthenticated(false);
}
});
};
getAuth();
}, [redirectTo]);
if (isAuthenticated) {
return children;
}
return <Navigate to={redirectTo} />;
}
getAuth is an async function, so it will return a Promise. You have to either await its output or use .then to work with the resolved promise.
Side note, it's usually preferable to either use async/await or .then, but not both.