diff --git a/packages/generouted/readme.md b/packages/generouted/readme.md index 03352c9..531e52d 100644 --- a/packages/generouted/readme.md +++ b/packages/generouted/readme.md @@ -441,6 +441,96 @@ Via `@generouted/react-router/core` or `@generouted/solid-router/core`
+## FAQ + +
+How to implement protected or guarded routes? + +
+ +There are multiple approaches to achieve that. If you prefer handling the logic in one place, you can define the protected routes with redirection handling within a component: + +```tsx +// src/config/redirects.tsx + +import { Navigate, useLocation } from 'react-router-dom' + +import { useAuth } from '../context/auth' +import { Path } from '../router' + +const PRIVATE: Path[] = ['/logout'] +const PUBLIC: Path[] = ['/login'] + +export const Redirects = ({ children }: { children: React.ReactNode }) => { + const auth = useAuth() + const location = useLocation() + + const authenticatedOnPublicPath = auth.active && PUBLIC.includes(location.pathname as Path) + const unAuthenticatedOnPrivatePath = !auth.active && PRIVATE.includes(location.pathname as Path) + + if (authenticatedOnPublicPath) return + if (unAuthenticatedOnPrivatePath) return + + return children +} +``` + +Then use that component (`` ) at the root-level layout `src/pages/_app.tsx` to wrap the `` component: + +```tsx +// src/pages/_app.tsx + +import { Outlet } from 'react-router-dom' + +import { Redirects } from '../config/redirects' + +export default function App() { + return ( +
+
+ +
+ +
+ + + +
+
+ ) +} +``` + +You can find a full example of this approach at [Render template](https://github.com/oedotme/render/blob/main/src/config/redirects.tsx) + +
+ +
+ +
+How to use with Hash or Memory Routers? + +
+ +You can use the exported `routes` object to customize the router or to use hash/memory routers: + +```tsx +import { createRoot } from 'react-dom/client' +import { RouterProvider, createHashRouter } from 'react-router-dom' +import { routes } from '@generouted/react-router' + +const router = createHashRouter(routes) +const Routes = () => + +createRoot(document.getElementById('root')!).render() +``` + +
+ +
+ +
+ ## License MIT