I've built my own component, which works broadly as follows:
- Sets two variables, by pulling values from local and session storage
- If JWT doesn't exist, then navigate user to the sign in screen
- If JWT exists, but session storage doesn't, then verify JWT is valid. If so, set session storage and return the 'children' component.
- If JWT exists and session storage exists, then return the children.
When I run this though, if the session storage doesn't exist (i.e. step 3 runs) then it just returns a blank screen with no error message.
If session storage is present (i.e. final step is valid), then it runs as expected - and I have absolutely no idea why.
Here's my component:
const PrivateRoute = ({ children }) => {
let isAuthenticated = localStorage.getItem('auth')
let hasAuth = sessionStorage.getItem('husi')
if (!isAuthenticated) {
return <Navigate to="/sign-in" replace />
}
// Check if a token exists && state of auth
if (isAuthenticated && !hasAuth) {
console.log("Stage 1")
axios.post("/api/checkAuth", {
token: JSON.parse(isAuthenticated)
})
.then(() => {
console.log("Stage 2")
sessionStorage.setItem('husi', 'indeed')
})
.then(() => {
console.log("Stage 3")
return children
})
.catch((err) => {
localStorage.clear('auth')
return <Navigate to="/sign-in" replace />
})
} else if (isAuthenticated && hasAuth) {
console.log("Stage 4")
return children
}
}
Any feedback would be appreciated!