Blog>
Snippets

Handling 404 Pages with TanStack Router in SSR

Implement a 404 error page using TanStack Router in a SSR setup, showing how to configure fallback routes for unmatched paths.
import { createBrowserRouter, RouterProvider, Route } from 'react-router-dom';
Import necessary components and functions from react-router-dom.
import { renderToString } from 'react-dom/server';
Import renderToString from react-dom for server-side rendering.
import App from './App';
Import the main App component.
import NotFoundPage from './NotFoundPage';
Import the NotFoundPage component that will be displayed for unmatched routes.
const router = createBrowserRouter([
    { path: '/', element: <App /> },
    { path: '*', element: <NotFoundPage /> }
]);
Create a router instance using createBrowserRouter. Define routes for the application and a fallback route (*) that matches any path not previously matched, rendering the NotFoundPage.
const renderPage = async (req) => {
  const element = <RouterProvider router={router} />;
  const html = renderToString(element);
  return { html };
};
Define an async function to render the application server-side. It takes the incoming request, uses RouterProvider to pass the router configuration, and then renders it to a string.
export { renderPage };
Export the renderPage function for server-side use, allowing the server to use it to handle incoming requests and render the appropriate component.