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:

app/routes/_index.jsx
12345678910111213141516
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:

components/CountryGreeting.jsx
123456789
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:

app/routes/_index.jsx
1234567891011121314
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

Specify the value to return when the evaluation cannot complete:

app/routes/_index.jsx
12345678910
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};}