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:
- Pre-fill the feature cache
- Render server side using using
useFeature()
as you normally would. - Send the cache to the client
- 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
- Create a
getServerSideProps
method to enable SSR. - Within the method create a session, and request a cache fill using
requestCacheFill()
. - 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 notfeatures
- 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.