-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[web-router] protected routes, how to implement them? #79
Comments
It might be worth using something like this const protect = (factory: ComponentFactory) => {
return component((props = {}) => {
const { isLoggedIn } = useAuth();
useLayoutEffect(() => {
if (!isLoggedIn) {
// redirect to login page
}
}, []);
return isLoggedIn ? factory(props) : null;
});
};
export const routes = [
{
path: '/',
component: Root,
children: [
{
path: '',
component: protect(lazy(() => import('./pages/Dashboard'))),
},
{
path: 'login',
component: lazy(() => import('./pages/Login')),
},
{
path: 'not-found',
component: lazy(() => import('./pages/NotFound')),
},
{
path: '**',
redirectTo: 'not-found',
},
],
},
]; |
Thank you for the lead. I think I got something working const AuthContext = createContext(null)
export const useAuth = () => useContext(AuthContext)
// Wrap app
const AuthProvider = component(({ slot }) => {
const api = useApi()
const { isFetching, data, error } = useQuery('retrieveAdmin', api.retrieveAdmin)
if (isFetching && !data) {
return <div>Loading...</div>
}
return <AuthContext value={{ isFetching, data, error }}>{slot}</AuthContext>
})
export default AuthProvider
// Wrap pages that require auth
export const withAuth = (factory) => {
return component((props) => {
const { error } = useAuth()
if (error) {
const history = useHistory()
history.push('/login')
return null
}
return factory(props)
})
}
// Login.jsx
const Login = component(() => {
const { data } = useAuth()
// redirect to dashboard if logged in
if (data) {
const history = useHistory()
history.push('/')
return null
}
return (
<>
login form
</>
)
}) |
I noticed that the code above doesn't actually work as expected with SSR. One possibility would be to only redirect on the browser, moving history.push in useEffect, but I would like the server to render the correct page. |
Such actions are usually done through effects. In reality,
Sounds like a reasonable solution.
This would require the router to implement some method that would synchronously check the rights to the route when building the route tree. There is no such method in this implementation. |
Not only through server, but on first requests to the server in a isomorphic fashion. It's mostly an optimization to immediately deliver the login page html, for a faster perceived response time. |
Web router expects factory functions in the
component
field, which means I cannot doI also cannot do
How does one implement "protected routes" with web-router?
The text was updated successfully, but these errors were encountered: