How to use @frontegg/react
with React Router v6 and v7
Frontegg supports client-side routing with React Router v6 and v7. To implement such routing in your application with @frontegg/react
, please refer to the example below:
import React from "react";
import ReactDOM from "react-dom/client";
import { RouterProvider, createBrowserRouter } from "react-router-dom";
import { FronteggProvider } from "@frontegg/react";
import App from "./App";
import { Root } from "./Root";
import { Settings } from "./Settings";
const contextOptions = {
baseUrl: "[your-base-url]",
clientId: "[your-client-id]",
};
const routes = [
{
path: "/*",
element: (
<FronteggProvider contextOptions={contextOptions} hostedLoginBox={true}>
<App />
</FronteggProvider>
),
children: [
{ path: "", element: <Root /> },
{ path: "settings", element: <Settings /> },
],
},
];
const router = createBrowserRouter(routes);
const root = ReactDOM.createRoot(document.getElementById("root") as HTMLElement);
root.render(<RouterProvider router={router} />);
Login method
Login method
Switch to hostedLoginBox={false}
if you're using @frontegg/react
with the embedded login implementation
Inside your <App />
component you should render the react-router <Outlet>
to allow nested routes as below:
import { Link, Outlet } from 'react-router-dom';
//...
<div>
<Link to="/settings">Open Settings route</Link>
<div>
<div>
<Outlet>
</div>
How to protect specific routes
If you would like to check that the user is authenticated only on specific routes, you could implement a method similar to the below example in your code:
import { FC, useEffect } from 'react';
import { useAuthRoutes, useAuthUserOrNull, useIsAuthenticated } from "@frontegg/react";
import { useLocation, useNavigate } from "react-router-dom";
const ProtectRoute: FC = (props) => {
const user = useAuthUserOrNull();
const navigate = useNavigate();
const location = useLocation();
const { loginUrl } = useAuthRoutes();
const isAuthenticated = useIsAuthenticated();
useEffect(() => {
if(!isAuthenticated) {
navigate([loginUrl, '?redirectUrl=', encodeURIComponent(location.pathname + location.search + location.hash)].join(''))
}
}, [navigate, loginUrl])
if (isAuthenticated && user)
return <>{props.children}</>;
return null;
};
export default ProtectRoute;