All questions

How do I gate a feature in a server component based on a CQL condition?

Asked by leo_builds on

Lleo_builds

i have a promo block I only want to show returning visitors, and I want that decided on the server so there is no hydration flash where the wrong version paints first.

What does the evaluate flow look like in an App Router server component, and how do I make it fail safe so a hiccup in evaluation does not crash the whole page?

Was this helpful?

2 answers

ABAisha BelloAccepted answer

Evaluate the condition server-side and branch on the boolean it returns. The pattern is evaluate plus a catch that returns false, so a failed evaluation hides the gated feature instead of throwing:

import {cql} from '@croct/plug-next/server';
export default async function Page() {  const isReturning = await cql`user is returning`.catch(() => false);
  return (    <>      <Hero />      {isReturning && <PromoBlock />}    </>  );}

Because the decision happens on the server, the branch never reaches the client, so there is no flash of the wrong variant after hydration. The one thing to know: the cql tagged template is App Router only. Outside App Router you use evaluate instead, which is covered in the cql tagged template is App Router only.

Was this helpful?
Lleo_builds

the evaluate plus catch does exactly what I wanted, no flash and the block just quietly stays hidden if anything goes wrong. thanks

Bben.h

That is the right call when the decision can live on the server. If you have a case that genuinely has to stay client-side, for example gating on something only known after an interaction, there is a useEvaluation hook for that. It reads the same conditions but from a client component. Rundown in the useEvaluation feature flag pattern.

Was this helpful?
Still have questions?