Blog>
Snippets

Integrating TanStack Config with Next.js for Server-Side Rendering

Showcase how to integrate TanStack Config with Next.js for server-side rendering, including fetching initial state.
import { createRouter } from '@tanstack/react-location';
import { hydrateRoot } from 'react-dom/client';
import { ReactLocationServer } from '@tanstack/react-location-server';
import App from './App'; // Assume this is your main App component

const router = createRouter({
  routes: [{ path: '/', element: <App /> }],
});

export async function getServerSideProps(context) {
  const locationServer = new ReactLocationServer({
    requestInfo: {
      path: context.req.url,
    },
  });

  await router.match({
    location: context.req.url,
    context: locationServer,
  });

  const initialState = locationServer.getInitialState();

  return { props: { initialState } };
}
This code snippet demonstrates how to integrate TanStack Router with Next.js for server-side rendering. The 'getServerSideProps' function is a Next.js function that runs on server-side for pre-rendering. Inside it, we instantiate ReactLocationServer with the current request path, match the route using TanStack's router, and then extract the initial state which will be passed as props to the component.
function MyApp({ Component, pageProps, initialState }) {
  return (
    <Component {...pageProps} initialState={initialState} />
  );
}

export default MyApp;
Here we define the main application component for Next.js that receives the initialState as a prop from 'getServerSideProps' and passes it down to the rendered page component. This enables SSR with initial state preloading using TanStack Config.
import { useHydrateAtoms } from 'jotai';
import { atom } from 'jotai';

// Assuming you're using Jotai for state management
const initialStateAtom = atom({});

function Page({ initialState }) {
  useHydrateAtoms([[initialStateAtom, initialState]]);

  // Render your page component
  return (<div>Your Page</div>);
}
In the page component, we use 'useHydrateAtoms' from Jotai (assuming Jotai for state management) to hydrate the state with the initial state received from server-side. This ensures the component has access to the initial state preloaded on the server, enabling a seamless integration of server-side data with the client.