What is a semantic layer and why do your metrics need one?

Monday's revenue dashboard shows $410,000. The account team's dashboard says $445,000 for the same week. Both use the warehouse. Both reports refresh on time. After an hour of tracing SQL, an analyst finds that one report counts paid invoices and the other sums invoice lines after joining them to subscription amendments. “Revenue” is doing too much work as a column label.
A semantic layer gives business concepts such as a customer, a completed transaction, or net revenue an explicit, reusable definition over the underlying data. Depending on the implementation, it can describe entities, dimensions, relationships, aggregations, time rules, and which metrics consumers can query. Its value shows up when someone asks a new question and the system still applies the agreed logic without that person copying last month's dashboard SQL.
Locate the rules that turn a row into a business fact
A warehouse stores records and can execute queries. A transformation can produce a clean table at the grain of one row per invoice. A semantic layer expresses that invoice amount sums across invoices, that an invoice belongs to an account, and that the finance team's recognized revenue metric may book on a different date from cash received. A dashboard asks a particular question about those definitions. All of these parts can live in the same technical stack. The distinction is what decision each part owns.
The dbt Semantic Layer, for example, lets teams define business metrics in a modeling project for use across downstream tools. Other systems provide semantic models inside a BI application, or teams expose a carefully governed collection of SQL views for a smaller set of questions. You do not need a new product to discover whether you have a semantic problem. Ask two knowledgeable analysts to implement a metric independently, then inspect where they made different reasonable choices.
Give one metric a definition a reviewer can test
“Active workspace” sounds straightforward until people try to use it. Is a workspace active when a member signs in, when a background sync executes, or when someone completes meaningful work? Are internal accounts eligible? Does the reporting week use UTC, the workspace's local time, or the finance calendar? Does an account deleted today disappear from last quarter's result? Each choice can change a number while leaving the SQL syntactically valid.
| Part of the contract | Example for a weekly active workspace |
|---|---|
| Entity and identity | One stable workspace ID, retained through display-name changes |
| Qualifying action | At least one successful human edit to a shared document |
| Time assignment | Week of the edit occurrence in the stated reporting time zone |
| Exclusions | Test tenants and automated maintenance actions identified by explicit fields |
| Aggregation | Distinct workspaces per selected interval; monthly totals require a fresh distinct count |
| Reporting dimensions | Plan at the time of the qualifying action, with a policy for unknown values |
The final row is a frequent source of silent disagreement. If a customer upgrades on Friday, the product team may want to know how the account behaved while it was on the free plan. A sales manager may want to slice the same history by the account's current plan. Both can be legitimate. Give the dimensions different names and specify how to use them. Replacing every historical plan with today's plan should be an explicit choice rather than an incidental result of a join.
Decide which disagreement the layer can resolve
A coherent semantic model helps when three teams agree on what a renewal is but implement the cancellation grace period differently. It cannot decide what the company should count as renewal. Nor can it recover a payment timestamp the source system never recorded. Put unresolved business decisions in front of the right owner and identify missing instrumentation before treating a new model as a fix.
Also check whether consumers actually use the definition. A catalog entry can explain the correct formula while an embedded dashboard keeps executing an old one. Ask for a trace from the display name through the generated or maintained query to a few source records. Check who can query those records, who can change the definition, and who learns when its meaning changes. A shared definition becomes useful when a consumer can discover it, invoke it, and verify it.
Model what one row represents before you expose a metric
A repair company wants a daily total of technician minutes spent on completed visits. Dispatch also wants to know which faults technicians encountered. One visit can resolve several faults. The warehouse stores the visit duration once and gives each fault its own row. Both tables are correct. A dashboard that joins them can publish an incorrect number without encountering a single missing value or database error.
Name the entities, measures, dimensions, and clock
The entity is the thing a record identifies or connects to another record. In the visit table, visit_id identifies one completed repair visit. In the fault table it points back to that visit and can repeat. The grain describes what a row means. The visit table has one row per visit. The fault table has one row per distinct visit and fault-code pair. Describing both as “repair data” loses the information the query engine needs.
The measure is the quantity along with its aggregation. Here it is the sum of recorded labor minutes at visit grain. A dimension gives the user a way to break that measure down. Each visit has one completion date and could have one service region recorded at completion. Fault code is more complicated because one visit can have several. MetricFlow's semantic model illustrates how entities and dimensions guide the construction of metric queries. The names and configuration syntax vary across products. The relationship between visit and fault must be accurate whichever tool compiles the query.
Specify the clock alongside the measure. This metric assigns the whole duration to the UTC day the visit was completed. A visit that started at 23:45 and ended at 00:15 contributes 30 minutes to the second day. A staffing report that asks how many minutes technicians worked during each day would split that visit across two dates. Those are distinct business questions. Give the second calculation its own definition before asking a daily trend chart to answer it.
Write a testable metric definition
Use the KPI guide to choose an outcome, denominator, and observation window your team can implement consistently.
Read the KPI PlaybookReproduce the join that overstates the total
Run the following SQL blocks in order in one fresh SQLite session. The example uses temporary tables. The foreign key expresses the relationship, and the composite primary key prevents a repeated fault code on the same visit. Visit 103 deliberately has no fault classification.
Now join the tables and sum the duration. The two diagnostic columns make it possible to see the mistake in the result itself.
The result is four joined rows, three visits, 100 reported minutes, and 60 distinct minutes. The source visits total 80 minutes. Visit 101 contributes twice to the first sum. Adding DISTINCT inside the second sum collapses the two genuinely separate visits with the same duration. SQLite's aggregate functions apply that modifier to values of the expression. Two equal measurements remain two observations when they belong to different visits.
Preserve the visit grain when adding another measure
Dispatch might want both total labor minutes and the number of recorded faults in a daily report. Aggregate the faults to one row per visit before joining them. The left join retains visit 103, and the default of zero applies to its recorded-fault count. The labor value comes from the visit record.
The result for November 3 is three visits, 80 minutes, and three recorded faults. The query works because the right side can match at most one row per visit. Some semantic systems can generate other valid forms automatically. For example, Looker's symmetric aggregates use unique record keys and declared relationships to protect supported aggregates against fanout. A declared unique key that actually repeats undermines that protection.
Slicing by fault still requires a policy. For “minutes on visits involving a battery fault,” select each matching visit once, then sum its minutes. For “minutes attributable to fixing batteries,” the fixture lacks a time allocation between the battery and display work on visit 101. Reporting that visit under both categories can answer a visit-involvement question, but summing the category totals would double count it. Put that limitation next to the dimension, or collect fault-level time if the allocation decision matters.
For example, filtering for visits involving a battery returns visits 101 and 102 for 40 minutes. Filtering for a display returns visit 101 for another 20 minutes. Across either fault there are still only two qualifying visits and 40 minutes of work. Adding those two filtered totals would silently assign another 20 minutes to the team.
Keep this fixture as an acceptance case for the semantic definition. Check the expected total, the visit with two faults, the equal durations, and the unclassified visit. When reusing the result elsewhere, inspect the fact table and metric definition and preview the metric on warehouse data. A total that changes when a descriptive table is joined is a concrete reason to inspect the relationship before publishing the chart.
Reuse one metric across a dashboard, an experiment, and a conversation
Suppose a collaboration product defines an activated workspace as one where two distinct people edit the same project within seven elapsed days of workspace creation. The definition names the entity, qualifying events, relationship between the people, start time, and observation window. It gives the PM enough information to challenge a number. Two editors working on separate projects don't qualify. One person editing under two device IDs doesn't qualify either. The model needs a defensible mapping from device to person and a stable project and workspace key.
The weekly dashboard takes workspaces created in a given week as its cohort. Suppose 200 workspaces have completed their seven days of follow-up and 50 meet the definition. The dashboard shows 25% activation. If the team instead asks how many workspaces activated during the week, some of the successful workspaces may have been created the previous week. Moving the date filter from creation time to activation time changes the population. Both views can be useful. Give them distinct labels so a change in question doesn't look like a disagreement between teams.
Keep the experiment's population attached to its result
Now test a new project-sharing flow on 120 of those workspaces. Assume all 120 were eligible and assigned at creation, and all have a mature outcome window. Among 60 control workspaces, 12 activate. Among 60 treatment workspaces, 18 activate. The experiment reports 20% and 30%, a difference of 10 percentage points. Both arms together contributed 30 activations. The other 80 workspaces contributed 20, so the company dashboard still reports 50/200. The product dashboard and the experiment reached their numbers from the same event definition.
The reported 10-point difference is a sample estimate with uncertainty. A chart comparing all new workspaces this week with all new workspaces last week answers a different question about an aggregate change over time. It does not recreate random assignment. In GrowthBook, Product Analytics can reuse metrics defined for experimentation. Preserve the analysis settings around those metrics too. If a future experiment assigns established workspaces 30 days after creation, the original seven-day activation outcome occurred before treatment and can't measure the effect of that intervention.
Know which quantities can be added
A semantic layer should encode enough aggregation behavior to prevent a reasonable-looking subtotal from becoming the wrong answer. The dimensional modeling distinction between additive, semi-additive, and non-additive facts gives an analyst three practical tests.
- Additive. The number of distinct qualifying activation events can be added across disjoint creation cohorts if each workspace contributes at most one activation and belongs to exactly one cohort. A workspace tagged to two sales regions breaks that assumption when totals are rolled up across regions.
- Semi-additive. A count of paid seats at the end of a day can be added across disjoint accounts at the same moment. Adding Monday's 100 seats to Tuesday's 105 gives 205 seat-days if both are daily snapshots. It does not give Tuesday's seat balance. A period-end balance needs the appropriate end-of-period observation, with a defined policy for missing snapshots. Analysis Services' semi-additive behavior illustrates how a measure can aggregate differently over time than across other dimensions.
- Non-additive. Activation rates must be recomputed from compatible counts. A group with 5 activations out of 10 workspaces and another with 9 out of 90 combine to 14%, assuming the groups are disjoint. Averaging their rates gives 30% and gives the small group as much weight as the large one. Store or recover both components.
Be especially careful with breakdowns based on a member's role or device. A workspace may have an editor on an Android phone and another on a laptop. Counting that workspace under both devices can be correct in a breakdown about participation. Summing those groups to produce overall activation double-counts the workspace. Decide which dimensions partition the entity and which ones overlap. A semantic query engine such as dbt's MetricFlow uses modeled entities and relationships when constructing queries, but the team still has to describe the business relationships accurately.
Ask a conversational analyst a reproducible question
“How is activation doing?” leaves nearly every important choice open. Try “For workspaces created in October that have completed seven days of follow-up, show activated workspaces and eligible workspaces by creation week, using the shared activation metric.” Ask the analyst to return both counts, the metric version or definition, date field, cutoff, and any filters. Reproduce one week from the dashboard before adding a region breakdown. GrowthBook's conversational analytics workflow lets a reader open the returned chart and review or adjust the exploration.
When two answers disagree, compare their eligibility, time anchor, denominator, grouping, and data freshness in that order. If these match, trace a handful of workspace IDs through the joins. If they differ by design, keep both numbers and name the distinction in the report. A shared definition saves teams from writing three versions of activation. It still leaves the reader responsible for knowing whether a number describes all new workspaces, a randomized cohort, or only workspaces that have finished their observation window.
Change a shared metric without rewriting the company's history
A weekly report says 1,000 paying workspaces were active. The analyst learns that the current definition counts an automated sync as activity, even when nobody has opened the product. Customer success uses the number to decide which accounts need help. Finance uses it to forecast infrastructure demand. Both teams have a reasonable interest in activity. They have different reasons for counting it. A semantic layer can make that disagreement visible before one team changes a definition that the other relies on.
Ask the metric owner which question the proposed change answers. For customer success, define “weekly engaged paying workspaces” as distinct paid workspaces with at least one qualifying human action in the reporting week. Keep the existing activity measure for infrastructure planning if background jobs create real load. Give each measure a stable identifier and a plain-language description. Name the person who owns the business interpretation and the person who can trace the warehouse implementation. These can be different people. The first decides whether an action is evidence of engagement. The second verifies the action has been recorded reliably since the relevant date.
Test the definition against cases you can explain
Construct a small reference dataset before running both metrics over a full quarter. Include a paid workspace with a human edit, one with only an automated sync, one with both actions, and one whose subscription changes midweek. Add a retry of the same edit, and put one event on the week boundary in the agreed reporting time zone. Write down the expected membership of each workspace. If the owner can't decide how to treat the subscription change, the missing input is a business rule. A technically valid query can implement either choice.
Then run both measures on the same historical interval. In this example, suppose 140 of the 1,000 active workspaces had only automated syncs and all the others had at least one eligible human action. The new measure should count 860. A workspace with both a sync and a human edit remains in the count once. If the actual result is 820, pull the 40 unexpected exclusions and trace them. A filter on the wrong event producer or a join to today's subscription state can remove exactly the customers a weekly lifecycle report needs to find.
Validate both the model and its consumers. A configuration check can catch an undefined measure. It won't know whether the Thursday edit should count, or whether a regional dashboard can still resolve a renamed field. In Looker, for example, model data tests and content validation cover different failure modes. Apply the same distinction in your own stack. Check the expected values, then open the report, scheduled export, and experiment readout that rely on them with the permissions their normal users have.
Decide which historical series to publish
A customer-success leader comparing this quarter with last quarter needs a consistent engagement series. If the historical source contains the necessary human-action signals, backfill both quarters under the new definition and label them accordingly. Preserve the old figure and the definition that justified decisions at the time. If older events lack a reliable human-versus-automation marker, start the new series at the earliest defensible date and annotate the break. An invented classification would give the chart continuity at the expense of its meaning.
Publish the new identifier alongside the old one while named consumers migrate. The dbt model versioning workflow illustrates how a producer can maintain versions of an upstream model while downstream users adopt a breaking change. Your semantic tool may handle metric versions differently. The practical test is whether a consumer can deliberately select a definition and reproduce last month's readout, including the relevant data cutoff.
Before retiring the old measure, check usage by service accounts and scheduled jobs as well as dashboard views. Have each owner reconcile one reporting period and record when the switch happened. Retain a readable change note explaining the 140-workspace difference. The first employee to see the new report should be able to answer “Did fewer customers use the product?” without opening a support ticket with the data team.
Start with the metric that causes a recurring argument
Choose an outcome with two active consumers and a visible disagreement. Write the grain, identity, time basis, and permitted joins beside the metric. Build a small fixture where a naive query returns a plausible wrong answer. Give the dashboard owner and the experimentation analyst the same inputs and ask each to explain the correct totals for their population. That exercise will tell you which business logic belongs in the shared model and which context should remain explicit at the point of analysis.
For a team already working in GrowthBook, Product Analytics can reuse metrics defined for experimentation. Use that shared definition to test one historically troublesome outcome. If the trend and the experiment differ, compare their units, windows, and eligibility before editing the underlying metric. A mature semantic layer lets a colleague explain why two correct numbers differ and who should investigate when two numbers that ought to agree do not.
Try one shared warehouse metric
Connect a data source to GrowthBook and use a documented metric to compare a product trend with an experiment readout.
Explore GrowthBookRelated Articles
A magazine's home page shows two recent issues. The design team wants subscribers to try a shelf with four. All four covers are public, and changing editions while the page is open should update the shelf immediately. That gives you a small React feature with a useful acceptance test. Click from guest to subscriber and back, and count the covers each time.
We'll put the display limit in a typed local flag, evaluate it inside a React component, and leave the choice of edition with the app. The example runs in a client-rendered React app without a GrowthBook account, an SDK key, or a request for flag rules. For the wider workflow, free feature flags for coding agents explains what to ask an agent to implement and how to review the result.
Define what one flag controls
Start with an existing React and TypeScript app, or create a Vite React project for the example. Install both GrowthBook packages so the definitions and the hooks resolve against compatible SDK versions.
Create src/flags.ts. Here the feature value is a number, which lets the component use the same rendering code for either edition. A future change from four covers to three is one edit to the rule.
A guest falls through to the default of two. A subscriber matches the rule and gets four. This rule applies to every subscriber, so the ID has no effect on the result here. If you later roll the shelf out to a percentage of subscribers, you already have an identity to use for repeatable assignment.
The type registration release note explains the version requirement for LocalFeatures. The registration connects the definition, the attributes, and the value returned by the hook. For the TypeScript mechanics, see Jeremy Dorn's Register pattern walkthrough.
Put the current reader above the shelf
Replace src/App.tsx with the component below. The edition switch is a local fixture so anyone reviewing the change can reproduce both states. In an existing app, take those two values from the active reader in your session layer.
The provider receives an instance initialized with the current reader and the checked-in rules. React can render the correct shelf on the first pass for that reader. If the app is still loading a session, decide what should occupy the shelf in the meantime. For this public list a two-cover guest view is reasonable. On a page where a switch would interrupt the reader, wait for the session before mounting the shelf.
Give your agent the React setup
Use the local flags guide to ask for a typed definition, a provider with the current reader, and a test that changes the edition.
Open the Agent GuideThe useMemo dependencies include the ID and the edition. If a reader subscribes while signed in, their ID can stay the same while their edition changes. Depending only on the ID would leave the old SDK instance in place. Passing a fresh object as the dependency on every render would create unnecessary instances. The example uses the two primitive values the rule setup actually needs.
Read the numeric flag where React renders the list
Create src/IssueShelf.tsx. Keep one stable ID per issue and let the component use the resolved value to select how many items to render.
Keep the hook at the top of the component, inside the provider's subtree. The React SDK supplies the flag value through that provider. Calling a hook inside a click handler or inside the list loop would break the Rules of Hooks. Use the returned number in ordinary render logic.
There are two places you can see the number two in this implementation. The definition's defaultValue is what an ordinary guest gets through evaluation. The 2 passed to the hook is a fallback for a value the SDK can't supply. Giving them the same value makes the basic shelf a sensible fallback, but checking only the guest case would let a broken provider arrangement or missing definition go unnoticed. The subscriber case proves that the component actually received the rule.
The list keys identify magazine issues. Keep those keys independent of the flag. Switching from two covers to four should preserve the identity of the first two rows. There's also no need to remount the whole app with an edition-specific key. React preserves state according to component position and keys. For example, a search input outside the shelf shouldn't lose its text because someone subscribed.
Check the transition in both directions
Use the template's build script to type-check and bundle the app. Once that passes, start the dev server and open the local address it prints.
On first load, the page says guest and lists November and October. Click Switch edition. The same page should say subscriber and add September and August. Click again. The list should return to the original two issues, in order. This last check catches code that appends more results on upgrade and never removes them on downgrade.
For a compile-time check, temporarily replace the numeric fallback with the string "2". Run the build again and inspect the error on the hook call. Then restore 2 and rebuild. If the string compiles, check that src/flags.ts belongs to the same TypeScript project as the component and that the package manager resolved compatible core and React versions.
Look for the core package used by your app and by the wrapper. If the app has several incompatible installations, align the versions before diagnosing the JSX. A team using an existing build script should also confirm it actually runs the TypeScript checker.
Hand off a React change someone can review
Give your coding agent the one-shot local feature flags guide and a short description of the observable behavior. For this shelf, the request can be as specific as the test.
The shelf controls how many public titles to display. If your actual feature unlocks paid articles, enforce access when the server serves an article. A client-rendered flag only decides what to show in that browser. Whenever a change to the display limit can wait for a deployment, the small local file keeps the decision reviewable alongside the component. When an editor needs to change it between issues without an engineering release, compare the free GrowthBook options for managing flag rules.
Manage the shelf in GrowthBook
Start a GrowthBook workspace when your magazine team is ready to manage shelf rules between deployments.
Get Started with GrowthBookTwo customers download the same weekly report. One has agreed to preview a new CSV column. The other feeds the old two-column format into an importer. Both requests can land on the same Node.js process, and each needs the right file even if the other request arrives while the report is loading.
This tutorial builds that endpoint with one checked-in feature flag. The process loads the rules once. Each request supplies its own workspace attributes and receives its own evaluation. You can run the whole example on your machine without an account, a client key, or a flag server. The free feature flags for coding agents walkthrough introduces the local approach. Here we'll give the agent a server-specific test to pass.
Set up a small TypeScript service
Use Node.js 22 or newer for this example. In an empty directory, create an npm project that uses ES modules, install the core SDK, and add the TypeScript tools.
Create tsconfig.json at the project root. The sample runs TypeScript directly with tsx and checks types in a separate step. Type checking with tsx explains why the two commands serve different purposes.
The following files all live next to that configuration. The server imports ./flags.js even though the source file is flags.ts. That spelling follows TypeScript's Node.js module resolution for ESM and works with this runner.
Define the report contract in one flag
Create flags.ts. The public format has two columns. The sample preview workspace gets one additional column. The only targeting attribute the rule needs today is reportPreview. Carry the workspace ID too, so two people downloading a report on behalf of the same workspace can share an assignment if you introduce a percentage rollout later.
The SDK type registration update covers this rule syntax and the 2.2.0 minimum. If you misspell reportPreview in a condition or use a string where the boolean flag expects a value, TypeScript can point at the definition. The Register pattern also makes the same feature name available in other modules without threading a generic type through each handler.
Before you add the endpoint, decide what belongs to the process and what belongs to the request. The feature definitions are identical for both customers. Their identity and preview enrollment can differ. If a handler changes an attribute on a single shared user instance before awaiting a database query, another handler could replace that attribute before the first handler resumes.
Give your agent a server-side task
Use the one-shot guide to add checked-in rules. Ask your agent to keep workspace attributes local to each request and demonstrate both CSV formats.
Open the Local Flags GuideCreate a scope when the request arrives
Create server.ts. The Node.js SDK provides GrowthBookClient for the process and createScopedInstance for the current request. The two fixture paths below stand in for two authenticated workspaces. The server binds to the loopback address so you can exercise it locally.
The HTTP handler looks up a workspace, creates its scope, and holds that scope across an asynchronous operation. The short promise-based timer gives a second request time to arrive. In a real export, that's where the database or storage read would happen. Keep the stable client at module scope and the scoped instance inside the handler. If a formatter needs the decision, pass it the boolean or the scoped instance.
In production, resolve the workspace and its access rights from the authenticated session before reading the report. The two selectable paths here are fixtures for public sample data. A caller's choice of a header, query string, or workspace slug can't establish permission to read another customer's report. The endpoint also prevents shared response caching. If you cache real exports, the cache needs to distinguish the workspace and the report format, along with any other inputs that change the response.
Test two requests that overlap
In the first terminal, type-check the service and start it. A successful type check exits quietly. The next command prints the loopback address and keeps the server running.
Save the following as verify.mjs. In a second terminal, run node verify.mjs. Node's built-in fetch calls the local server. Strict assertions compare the full header and data row, including where each row ends.
You should see the single success line. Testing just the preview workspace proves that the code can add a column. Testing both responses catches the more expensive mistake of silently changing an existing customer's export. Keeping the old format assertion around is especially valuable when the downstream importer belongs to someone outside your team.
To check the compile-time boundary, temporarily change gb.isOn("includeUniqueReaders") to gb.isOn("includeUniqueReader") and rerun npx tsc --noEmit. The diagnostic should identify the misspelled key. Restore it before running the server again. A coding agent can include the before-and-after type check and the two CSV headers in its pull request.
Decide when to expand the report
When one preview customer is ready, leave everyone else on the default. If the next step is to enroll a fraction of workspaces, choose an attribute that matches the promise you're making. Hashing a workspace ID lets colleagues downloading the same report share a format. Hashing each user's ID could give two analysts in the same company different column sets. The one-shot guide shows how to express a percentage and hash attribute in a local rule.
A new rule in flags.ts reaches a process through your deployment. During a rolling deploy, the same workspace might hit old and new processes. If customers need a durable choice of export schema, keep supporting the agreed format in the API itself. When the operational requirement is to change targeting between deploys, you can keep the scoped evaluation in the handler and change how the process receives its rules. The free GrowthBook offerings overview covers Cloud Starter and self-hosting for teams that want to manage those rules.
Manage report targeting in Cloud
Create a GrowthBook workspace when the team supporting exports needs to expand the preview independently of a server release.
Get Started with GrowthBookYour conference agenda has a new “Show room” button. Reviewers should see it on the first page load. Everyone else should get the existing agenda. If a Server Component renders the old agenda and a browser hook independently decides to show the new button, the first HTML and the browser can disagree.
In the Next.js App Router, the server can make this decision once and pass a boolean to the interactive component. We'll define the flag in the repo, select the preview audience with a local test cookie, and verify the actual HTML for both visitors. Clicking the button will still work after hydration. You can follow along without a GrowthBook account or client key. If you're assigning this work to an agent, the free feature flags for coding agents walkthrough gives the background.
Keep the flag definitions on the server
Use a TypeScript App Router project, or create a small one with create-next-app. These paths assume the project has an app directory at its root. If yours uses src/app, put both app and lib under src so the relative imports still match.
Keep the starter's root layout. Create lib/agenda-flags.ts with the following code. The SDK type registration update explains how LocalFeatures checks the flag and its rule against the registered types. This setup requires version 2.2.0 or later.
The module can reuse the client and rules across requests handled by the same process. It only holds the current visitor's audience inside the function call. Two requests can therefore use the same flag file and get different results. The Node.js SDK documents the scoped client used under the App Router here.
This particular rule has no percentage and needs no visitor ID. The two audiences are sufficient. If the team later asks for a rollout to 10% of attendees, add a stable attendee or registration ID and choose which of those units should stay together. Jeremy Dorn's Register pattern article explains how a change to an attribute type reaches the call sites that construct it.
Read the cookie for this request
Create app/agenda/page.tsx. The static heading can render for everyone. The request-specific content sits behind a Suspense boundary, so the fallback can show a neutral loading message until the server has the cookie.
The App Router's cookies function reads the incoming request asynchronously. Read it inside the visitor-specific component. Keeping that read out of shared cached code lets the surrounding page reuse common content without treating one visitor's decision as another's. This placement also accommodates App Router projects using Cache Components.
Give your agent the Next.js setup
Use the local flags guide with a concrete request to evaluate one flag on the server and return the same decision to the browser.
Open the Local Flags GuideThe cookie in this demo is a convenient way to preview a public UI treatment. Anyone with that cookie can see the room label. To target paying attendees or private sessions, obtain the audience from the verified session on the server and authorize the underlying data separately.
Pass one decision to the interactive component
Create app/agenda/Agenda.tsx. It's a Client Component because a visitor can open and close the room details. Its initial branch comes directly from the boolean supplied by the page.
The client boundary takes a serializable prop. The component receives true or false. The SDK instance, targeting rules, and cookie handling stay in the server module. You don't need a React provider for this component because its only browser-side choice is whether the visitor has clicked the button.
Follow one page load through server rendering and hydration. For a preview visitor, the server can send a section with a “Show room” button. React's first client render gets the same showRoom value and starts with open set to false. Hydration attaches the click handler. Opening the room detail then updates component state and doesn't require another flag evaluation.
Verify the HTML and the click separately
Build the production app and start it on port 3100.
In a second terminal, save this as verify-agenda.mjs in the project root and run node verify-agenda.mjs. The test makes two requests to the same route and looks for a marker on the rendered section. A marker in the HTML helps catch an implementation that only adds the intended layout after JavaScript runs.
Now open http://localhost:3100/agenda in a fresh browser profile. You should see the session title without a room button. In that local page's browser console, set the demo cookie and reload.
Click Show room and look for Room 204. Click Hide room and the room should disappear. This second check proves the component became interactive. If the server response test passes but the click fails, inspect the browser console for a hydration error before changing the flag rules.
Remove the fixture and reload once more. The button should disappear and the agenda title should remain.
The reload is deliberate. Editing the cookie in an already open document doesn't rerun its Server Component. In your app, use the normal session-change flow to request a fresh server render when a visitor signs in, signs out, or leaves a preview group.
Choose where the next flag should be evaluated
For a decision needed in the initial HTML, give the agent an observable requirement. Ask it to show the two HTTP responses, then click the interactive control in the preview. The first check catches an incorrect layout. The second catches correct HTML that never becomes interactive.
If a later feature depends on an action entirely within the browser, evaluate whether its flag belongs in the client tree. The one-shot local flags guide covers both placements. This agenda only needs one server decision. Updating its checked-in rule takes a deployment. Keep that tradeoff in view if the event organizer needs to pause a preview while attendees are already arriving. For that case, compare GrowthBook’s free options for changing flags between deploys.
Manage the agenda rollout in Cloud
Create a GrowthBook workspace when the organizer needs to adjust a preview audience while your Next.js app is serving attendees.
Get Started with GrowthBookReady to ship faster?
No credit card required. Start with feature flags, experimentation, and product analytics—free.




