Blog>
Snippets

Setting Up TanStack Router for SSR

Configure TanStack Router in a server-side rendered JavaScript application, including the initial setup and route configuration.
import { createBrowserRouter, RouterProvider } from '@tanstack/react-router';
import { createServerRenderer } from '@tanstack/react-router/server';
import { renderToString } from 'react-dom/server';
import React from 'react';
import { App } from './App';
import { Root } from './routes/Root';
import { Home } from './routes/Home';
import { About } from './routes/About';
This code imports necessary modules from TanStack Router and React for server-side rendering. It also imports App, Root, Home, and About components which would be part of the routing setup.
const router = createBrowserRouter([
  {
    path: '/',
    element: <Root />, 
    children: [
      { path: '/', element: <Home /> },
      { path: 'about', element: <About /> }
    ]
  },
]);
Creates a browser router with the root, home, and about routes. The Root component acts as a layout with the Home and About routes as its children.
async function render(url) {
  const renderer = createServerRenderer(router);
  const result = await renderer.render({ request: { url: url } });
  return result;
}
Defines an asynchronous render function that uses TanStack Router's server-side renderer to generate HTML based on the current URL.
const server = require('express')();

server.get('*', async (req, res) => {
  const { markup } = await render(req.url);
  res.send(`<!DOCTYPE html><html><body>${markup}</body></html>`);
});

server.listen(3000);
Sets up an Express server that listens for all get requests. It uses the render function defined earlier to generate and send back a full HTML page with the rendered component for the current route.