Skip to main content

React SSR - Cache

This chapter shows the use Causal to server side render (SSR) using Next.js.

Please read Basic React Usage first. It provides context necessary for this example.

The outline of SSR in Causal is as follows:

  1. Pre-fill the feature cache
  2. Render server side using using useFeature() as you normally would.
  3. Send the cache to the client
  4. Hydrate (normal React hydration) client side using the exact same render code

Code walk through

Import from Causal

import {
Session,
SessionContext,
SessionJSON,
qb,
useSessionJSON,
} from "../causal";
import { getOrGenDeviceId, products } from "../utils";
import { ProductInfo } from "./react-example";

Implement an SSR data fetch method

  1. Create a getServerSideProps method to enable SSR.
  2. Within the method create a session, and request a cache fill using requestCacheFill().
  3. Use session.toJSON() to pass the session - and its cache - in the props.
export async function getServerSideProps(
context: GetServerSidePropsContext
): Promise<{ props: PageProps }> {
const product =
products[context.query.pid as keyof typeof products] ?? products["iphone"];

const deviceId = getOrGenDeviceId(context);
const session = Session.fromDeviceId(deviceId, context.req);
await session.requestCacheFill(qb().getRatingBox({ product: product.name }));

return { props: { sessionJson: session.toJSON(), product } };
}

Convert the JSON props back to a session

In the page render function, call useSessionJSON to convert back to a session, and then set the session context. Render the Provider component (as previously shown in Basic React Usage).

export default function Index(props: PageProps) {
const session = useSessionJSON(props.sessionJson);

return (
<SessionContext.Provider value={session}>
<ProductInfo product={props.product} />
</SessionContext.Provider>
);
}

Falling back to client side rendering

If the there is an issue with SSR, Causal will fall back to a client side render. Any non cached feature will render client side.

You can tell if an SSR occurred in a few ways:

  • If you clear browser Local Storage and then reload the page, in the browser dev tools network tab you will see a call to signal, and not features
  • If you look at the cached feature data in local storage, the origRender will be "ssr" if it successfully SSR’d

More examples

Causal has facilities for reporting cache hits, misses, and spurious reads. Please see getImpressionStats and clearImpressionStats.

We have a fully featured example showing usage of cache stats, as well as setting up a Next.js custom app to do the cache transfer for all pages. Please see the ssr-cache-stats for details.

Alternate methods

Another technique for SSR is to manually passing around the data collected in getServerSideProps. Please see SSR - Props for details.

Congrats

You've finished the SSR React with Next.js walk through.