Authentication Routes and Code Splitting
What you'll learn: How to split your app's bundles so unauthenticated users don't download authentication code, and authenticated users don't load public-only bundles.
Why Split Authenticated vs Public Routes
Imagine delivering two different catalogs to two types of customers — why send a premium member catalog to window shoppers, or vice versa? The same applies to your app's JavaScript bundles.
When you split your routes by authentication state, unauthenticated users only download the login/signup/public pages, while authenticated users only download the dashboard/profile/settings code. Each group gets a smaller, faster initial bundle.
The Pattern
You've already learned route-level splitting. Now apply it with authentication awareness:
const PublicHome = lazy(() => import('./pages/PublicHome'));
const Login = lazy(() => import('./pages/Login'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Profile = lazy(() => import('./pages/Profile'));
function App() {
const { isAuthenticated } = useAuth();
return (
<Suspense fallback={<Spinner />}>
{isAuthenticated ? (
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/profile" element={<Profile />} />
</Routes>
) : (
<Routes>
<Route path="/" element={<PublicHome />} />
<Route path="/login" element={<Login />} />
</Routes>
)}
</Suspense>
);
}
The logged-out user's browser never downloads Dashboard.chunk.js or Profile.chunk.js. The authenticated user never downloads PublicHome.chunk.js.
Bundle Boundary Strategy
Treat authentication as a major code boundary. Public and authenticated features rarely overlap, making this an ideal split point. Pair with Error Boundaries to handle chunk-loading failures gracefully.
Key Takeaway: Splitting routes by authentication state ensures users only download code relevant to their session, reducing bundle size and improving performance for both authenticated and unauthenticated experiences.