Blog>
Snippets

Server-Side Data Preloading with TanStack Router

Show how to implement server-side data preloading for a specific route with TanStack Router, ensuring that the required data is loaded before rendering the page to the user.
import { createServerData, Outlet } from 'react-location';
Import the necessary functions from react-location library.
const loadData = async () => {
  // Fetch the required data for the route
  const data = await fetch('https://api.example.com/data').then(res => res.json());
  return data;
};
Defines an asynchronous function to fetch data required for a specific route.
const serverData = createServerData(loadData);
Creates server data using the `createServerData` function and the `loadData` function to fetch data on the server side before rendering the page.
const routes = [
  {
    path: 'specific-route',
    element: <Outlet />, // Placeholder component that will render the children routes
    loader: serverData
  }
];
Defines the route configuration, specifying the path for the route that requires server-side data preloading and assigns the `loader` to use the created server data.