'Route from login page to root page doesn't work in Netlify
I have an admin panel. user can see the dashboard, after login. In the local host, it works well. But when I deployed it to Netlify, after showing the login page, and user login, a blank page appear.
I use react-router-dom v6.
function App() {
const loginCtx = useContext(LoginContext);
return (
<BrowserRouter>
<Suspense fallback={<LoadingSpinner />}>
<Routes>
{!loginCtx.isLogin ? (
<Route path="/" element={<Login />} />
) : (
<Route path="/" element={<MainLayout />}>
<Route index element={<Dashboard />} />
<Route path="/customers" element={<Customers />} />
<Route path="/customers/:customerId" element={<CustomerEdit />} />
<Route path="/products" element={<Products />} />
<Route path="/products/:productId" element={<ProductEdit />} />
</Route>
)}
<Route path="*" element={<NotFound />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}
export default App;
I'm useing redirects /* /index.html 200 in _redirects file.
Solution 1:[1]
Instead of conditionally rendering routes you might find you have better luck using an auth layout route that redirects to a "/login" route rendering the Login component or allows access through to a routed component.
Create an auth layout route that checks the loginCtx.isLogin value and conditionally renders an Outlet for nested Routes to be rendered into, or a redirect to the "/login" route.
import { Navigate, Outlet, useLocation } from 'react-router-dom';
const AuthLayout = () => {
const location = useLocation();
const loginCtx = useContext(LoginContext);
return loginCtx.isLogin
? <Outlet />
: (
<Navigate
to="/login"
replace
state={{ from: location }} // <-- current location so login can redirect back is desired
/>
);
};
Wrap the routes you want to protect with the new AuthLayout component, and move Login component into its own route.
function App() {
return (
<BrowserRouter>
<Suspense fallback={<LoadingSpinner />}>
<Routes>
<Route element={<AuthLayout />}>
<Route path="/" element={<MainLayout />}>
<Route index element={<Dashboard />} />
<Route path="/customers" element={<Customers />} />
<Route path="/customers/:customerId" element={<CustomerEdit />} />
<Route path="/products" element={<Products />} />
<Route path="/products/:productId" element={<ProductEdit />} />
</Route>
</Route>
<Route path="/login" element={<Login />} />
<Route path="*" element={<NotFound />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Drew Reese |
