Query evaluation
Learn how to evaluate CQL queries to personalize and segment your storefront.
Croct lets you evaluate CQL queries to personalize and segment your visitors. You can evaluate on the server in your loaders for flicker-free rendering, or on the client with a hook.
Server-side evaluation
Evaluate a query from a loader with the loader’s context, then render from the result:
import {useLoaderData} from 'react-router';import {evaluate} from '@croct/plug-hydrogen/server';
export async function loader({context}) { const country = await evaluate("location's country", { scope: context, });
return {country: country};}
export default function Index() { const {country} = useLoaderData();
return <p>Hello from {country ?? 'somewhere'}!</p>;}Client-side evaluation
To evaluate a query in a component, use the evaluation hook:
import {useEvaluation} from '@croct/plug-hydrogen';
export function CountryGreeting() { const country = useEvaluation("location's country", { initial: null, });
return <p>Hello from {country ?? 'somewhere'}!</p>;}Context variables
Add custom attributes to the evaluation context to enrich it with application-specific information. These values are accessible in the context variable:
import {evaluate} from '@croct/plug-hydrogen/server';
export async function loader({context}) { const isPremium = await evaluate("context's plan is 'premium'", { scope: context, context: { attributes: { plan: 'premium', }, }, });
return {isPremium: isPremium};}Fault tolerance
Always provide a fallback so that evaluation failures, such as network errors or timeouts, degrade gracefully instead of breaking the page.
Specify the value to return when the evaluation cannot complete:
import {evaluate} from '@croct/plug-hydrogen/server';
export async function loader({context}) { const country = await evaluate("location's country", { scope: context, fallback: null, });
return {country: country};}