Query evaluation

Learn how to evaluate queries in real-time.

This guide provides practical examples of using the Next.js SDK to evaluate CQL queries from your application.

Basic usage

To evaluate queries on the server-side, you can use either the evaluate or cql function.

Croct's mascot neutral
How about client-side rendering?

For client-side rendering, you can follow the React examples replacing the @croct/plug-react imports with @croct/plug-next.

Here is an example:

components/DocsLink.jsx
1234567891011
import {evaluate} from '@croct/plug-next/server';
export async function DocsLink() {
const isDeveloper = await evaluate("user's persona is 'developer'");
return (
isDeveloper
? <a href="/docs">View docs</a>
: <a href="/share">Share with your developer</a>
);
}

Note that the result of the evaluation is not limited to boolean values. For example, you can use the following query to find out the location from which the user is accessing your application:

components/Location.jsx
1234567
import {cql} from '@croct/plug-next/server';
export async function Location() {
const location = await cql`location`;
return (<address>{location.city}, {location.state} - {location.country}</address>);
}

In this case, the result of the evaluation is a geographic location, and the output would look like this:

Rendered output
<address>San Francisco, California - United States</address>

By the way, the example above is personalized using the <Personalization> component directly in MDX.

Fault tolerance

You should always provide a fallback value when evaluating queries to make your application resilient to unexpected errors, downtime, and network failures.

All you have to do is specify the result you want to use as a fallback:

components/Greeting.jsx
1234567
import {evaluate} from '@croct/plug-next/server';
export async function Greeting() {
const returning = await evaluate("user is returning", {fallback: false});
return returning ? 'Welcome back!' : 'Welcome!';
}

In this example, the result is set to false if the evaluation fails, ensuring that the application will work even if the evaluation fails.

Context variables

In some cases, you may want to pass additional information that can be used by the query in the evaluation process.

For example, let's say you want to check whether the user is accessing your application from one of a list of countries. The SDK allows you to pass this information as an attribute to the query:

components/ConditionalFeature.jsx
123456789
import {evaluate} from '@croct/plug-next/server';
export async function ConditionalFeature() {
const enabled = await evaluate("context's countries include location's country", {
context: {attributes: {countries: ['United States', 'Canada', 'Mexico']}},
});
return enabled ? 'Available' : 'Unavailable';
}

Any attribute passed in the attributes option will be available in the query as a context variable.