T
TanStackβ€’3y ago
genetic-orange

Protected Routes with auth state in redux

The authenticated routes documentation (https://tanstack.com/router/v1/docs/guide/authenticated-routes) show using beforeLoad like so:
const authenticatedRoute = new Route({
id: 'authenticated',
beforeLoad: async () => {
if (!isAuthenticated()) {
throw redirect({
to: '/login',
...etc...
const authenticatedRoute = new Route({
id: 'authenticated',
beforeLoad: async () => {
if (!isAuthenticated()) {
throw redirect({
to: '/login',
...etc...
to implement authenticated routes. My equivalent of isAuthenticated in this example is selecting into our redux store. I can see two options: a) get the ability to reference the redux store into the router context somehow b) move auth and redirect logic to the component itself a) seems better but it's not clear to me how I could wire this up. I guess i could place the whole store in the context like so:
const router = new Router({
routeTree,
context: {
store: myReduxStore
},
})
...in some route...
beforeLoad: ({ context: { store } }) => {
const isAuthenticated = isAuthenticatedSelector(store);
...etc...
const router = new Router({
routeTree,
context: {
store: myReduxStore
},
})
...in some route...
beforeLoad: ({ context: { store } }) => {
const isAuthenticated = isAuthenticatedSelector(store);
...etc...
Does this seem right?
5 Replies
rival-black
rival-blackβ€’3y ago
Hello πŸ‘‹ Personally I prefer to make a private layout (I use zustand but you can do the same with redux) and I use the router context to pass my state, which I use for auth. Maybe it can help you πŸ™‚
No description
No description
rival-black
rival-blackβ€’3y ago
There must be something better, I didn't think too much about it.
useful-bronze
useful-bronzeβ€’3y ago
hello toma .. i wanna ask somthing , why my route doesnt do redirect ? i also used zustand
No description
useful-bronze
useful-bronzeβ€’3y ago
Gist
how spesify authenticated routes?
how spesify authenticated routes? GitHub Gist: instantly share code, notes, and snippets.
rival-black
rival-blackβ€’3y ago
Oh @rickπŸ– it's because you're calling "useAuth" hooks outside of react. beforeLoad function is not a react component so you're breaking rules of hook. You have to use the getState() method from your zustand store : useAuth.getState() This enable you to use zustand states outside of react I think that's the problem, let me know

Did you find this page helpful?