I am currently trying to set up my routing for a new project. What I am attempting to implement is if a user access /home/user/settings and they are not logged in, it will redirect them to /login?redirectTo=/home/user/settings.
Or if they go to /home/device/claim?deviceid=123456789 and they are not logged in they will get redirected to /login?redirectTo=/home/device/claim?deviceid=123456789.
I currently have it working but I feel it cant be the best way of doing this. An issues I ran into when coming up with this idea were I don't know how many levels the URL will have.
My current code:
<Route>
<Route
path=":path1/:path2/:path3/:path4"
element={<RedirectAfterAuth />}
/>
<Route
path=":path1/:path2/:path3"
element={<RedirectAfterAuth />}
/>
<Route path=":path1/:path2" element={<RedirectAfterAuth />} />
<Route path=":path1" element={<RedirectAfterAuth />} />
<Route path="*" element={<Navigate to="/login" />} />
<Route path="login" element={<Login />} />
<Route path="/" element={<LandingPage />} />
</Route>
export default function RedirectAfterAuth() {
let { path1, path2, path3, path4 } = useParams();
let [searchParams, setSearchParams] = useSearchParams();
return (
<Navigate
to={`/login?redirectTo=${path1}${path2 ? "/" + path2 : ""}${
path3 ? "/" + path3 : ""
}${path4 ? "/" + path4 : ""}${searchParams ? "?" + searchParams : ""}`}
/>
);
}
I was wondering if there was a way to not have to put loads of different paths and account for all possibilities by just have a single param/searchparam.
Thank you for your time