T
TanStack2y ago
harsh-harlequin

Why context auth doesn't work if the router is lazy?

I want to put router lazy, but if a put the context it's not gonna work
import { createLazyFileRoute, redirect } from '@tanstack/react-router'
import Home from "@pages/home"


export const Route = createLazyFileRoute('/')({
beforeLoad: ({ context, location }) => {
if (!context.auth.isAuthenticated) {
console.log("context auth: ",context.auth.isAuthenticated)
throw redirect({
to: '/login',
search: {
redirect: location.href,
},
})
}
},
component: Home
})
import { createLazyFileRoute, redirect } from '@tanstack/react-router'
import Home from "@pages/home"


export const Route = createLazyFileRoute('/')({
beforeLoad: ({ context, location }) => {
if (!context.auth.isAuthenticated) {
console.log("context auth: ",context.auth.isAuthenticated)
throw redirect({
to: '/login',
search: {
redirect: location.href,
},
})
}
},
component: Home
})
3 Replies
sensitive-blue
sensitive-blue2y ago
The beforeLoad callback isn't available in the createLazyFileRoute function. https://tanstack.com/router/latest/docs/framework/react/guide/code-splitting#how-does-tanstack-router-split-code
Code Splitting | TanStack Router Docs
Code splitting and lazy loading is a powerful technique for improving the bundle size and load performance of an application. Reduces the amount of code that needs to be loaded on initial page load
sensitive-blue
sensitive-blue2y ago
You need to have both index.tsx for the critical configuration and index.lazy.tsx for the component code splitting.
harsh-harlequin
harsh-harlequinOP2y ago
Thanks 👍

Did you find this page helpful?