Skip to main content

React SSR - Props

note

Prepopulating the cache is the reccomended way to SSR.

This chapter explains how to explicitly pass SSR results as page props.

Please read Basic React Usage and React SSR - Cache first. They provide context necessary for this example.

Code walk through

Types

  • ImpressionJSON declares a JSON serializable version of an impression.

  • SelectFeatures<> declares a type that can be used both when getting an impression with useImpression, and when converting JSON back to an impression with toImpression. In VSCode, use a double quote (") to trigger autocomplete within the <>.

type SSRProps = {
product: (typeof products)[keyof typeof products];
json: ImpressionJSON;
};

type FeaturesToQuery = SelectFeatures<"RatingBox">;

Query impression and convert to JSON

In getServerSideProps:

  1. Use createQuery() to create the query
  2. Request the impression with useImpression.
    • useImpression is similar to the useFeature call we made in previous examples, but has more capabilities, such as being convertible to JSON and the ability to request multiple features.
  3. Convert the impression to JSON with toImpression, and return it as a page prop.
export async function getServerSideProps(
context: GetServerSidePropsContext
): Promise<{ props: SSRProps }> {
const product =
products[context.query.pid as keyof typeof products] ?? products["iphone"];

const query = createQuery<FeaturesToQuery>({
RatingBox: { product: product.name },
});

const impressionId = "imp-1234";

const session = new Session({ deviceId: getOrGenDeviceId(context) });
const { impression, error } = await session.requestImpression(
query,
impressionId
);

if (error) {
console.log(
"There is no impression server running yet, but it still works! " +
"Causal is resilient to network and backend outages because the defaults are compiled in 😃."
);
}

const props: SSRProps = { product, json: impression.toJSON() };
return { props };
}

Convert back to an impression and render

Convert the JSON back to an impression by calling toImpression() and render. Rendering is basically the same as the react-example.tsx.

export default function ProductInfo({ json, product }: SSRProps) {
const [rating, setRating] = useState(0);

const impression = toImpression<FeaturesToQuery>(json);

return (
<div className="center">
<h1>{product.name}</h1>
<img src={product.url} alt="product image" />

<h3>{impression.RatingBox?.callToAction}</h3>

{impression.RatingBox && (
<>
<RatingWidget
curRating={rating}
onSetRating={(newRating) => {
setRating(newRating);
impression.RatingBox?.signalRating({ stars: rating });
}}
/>
<a href={"ssr-props?pid=" + product.next}>Rate Another</a>
</>
)}
</div>
);
}

Congrats

You've finished the SSR props walk through.