SSR

Server side rendering

Overview

Server side rendering (SSR) allows each page to render the HTML on the server side by preloading the data needed for the render itself. SSR runs on each HTTP request.

SSR is usually needed for:

  • SEO
  • Faster client side rendering
  • Reduced JS bundle required for the initial load

SSR on a route

To enable SSR on a page you just need to create the same file with the rust extension:

  • src/routes/about.tsx
  • src/routes/about.rs

and then create a #[tuono_lib::handler] in the rust file, which will be the function called on each request before rendering the HTML.

Example

Suppose your page needs to pre-render frequently updated data (read from a local file). You can write a handler which reads a JSON file and passes it to the route like below:

// src/routes/about.rs
use tuono_lib::{Request, Response, Props};
use std::fs;

#[tuono_lib::handler]
async fn my_custom_ssr_page(req: Request) -> Response {
  let data = fs::read_to_string("my_data.json").expect("Failed to read json file");

  Response::Props(Props::new(data))
}

Once the data is loaded, you can access it through the data prop on the route.

To describe the structure of the props in TypeScript, you can use the TuonoRouteProps type. This type is designed to handle loading states in an application, making it easy to distinguish between when the data is still loading and when it has been successfully fetched and is ready to be used.

// src/routes/about.tsx
import type { TuonoRouteProps } from 'tuono'

interface MyData {
  name: string
}

export default function AboutRoute({
  isLoading,
  data,
}: TuonoRouteProps<MyData>) {
  if (isLoading) {
    return <>Loading...</>
  }

  return <>{data.name}</>
}
Edit page