After App Router dropped in Next.js pages feels genuinely faster for fully server rendered pages. But one thing that I don't quite like is page navigation. User always has to wait for the server call to finish.
App router navigation feels slow. For dashboards, this is quite unacceptable. Route doesn't change instantly when user clicks on something.
To bring back instant transitions without giving up SSR entirely, we use a hybrid setup
React Router!
Install React Router
Create a App Shell
"use client";
import dynamic from "next/dynamic";
const RouterApp = dynamic(() => import("@/components/router/router-app"), {
ssr: false,
});
const SpaPage = () => {
return <RouterApp />;
};
export default SpaPage;
Routes with React Router
# React Routes
import { BrowserRouter, Routes, Route, useParams } from "react-router-dom";
const Home = () => <div>Home</div>;
const About = () => <div>About</div>;
const UserProfile = () => {
const { userId } = useParams();
return <div>User Profile for ID: {userId}</div>;
};
const RouterApp = () => {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} /> {}
<Route path="/about" element={<About />} /> {}
<Route path="/users/:userId" element={<UserProfile />} /> {}
</Routes>
</BrowserRouter>
);
};
export default RouterApp;
Update Next.js config
module.exports = {
async rewrites() {
return [
{
source: "/((?!api|_next|_static|favicon.ico|.*\\..*).*)",
destination: "/dashboard/spa",
},
];
},
};
This gives us the best of both worlds, server-rendered entry and SPA-like snappiness once inside.