How to build a checkout experiment with Claude Code

A pull request can prove that both versions of a checkout summary render. It takes a different test to establish that the new summary helps more people complete checkout. Claude Code can help build both pieces, provided you give it a precise contract for what the code should do and what evidence will count as a result.
You'll build a Boolean flag called checkout-summary. Control keeps the existing text. Treatment uses revised text. The outcome is whether an assigned user completes checkout within seven days. By the end, you should have a repeatable local fixture, an exposure and outcome check, and a draft you can inspect in a GrowthBook demo project. Real traffic is a separate release decision with its own owner.
Define the experiment before opening the editor
Suppose support hears this question over and over again: “Is the amount on this screen what I'll actually pay?” The current summary leaves customers to interpret the relationship between the subtotal and the amount due. A revised summary could reduce uncertainty. It could also attract more attention to fees and cause more people to leave. Both outcomes are plausible. That makes this a candidate for an experiment.
Scope the change to the summary copy. Keep the payment processor, amount calculation, delivery options, button placement, and eligibility rule the same. If the agent also moves the payment button or changes how taxes are calculated, a difference in conversion will be much harder to interpret. Ask a reviewer to inspect the functional diff and the screenshots separately. Passing a screenshot comparison for the control state will not catch a change to the total sent to the server.
The workflow has three operating contexts. The local code and data examples use synthetic users and require no production credentials. Authenticated discovery reads a demo project's actual identifiers, settings, and metric definitions. Creating the draft modifies that demo project. Keep the target project visible in the request whenever you move between contexts. The Claude Code permission modes let you choose how the agent can act during different parts of the work.
Give the agent a brief it can test
Start with this prompt in your repository. Its first deliverable is a proposed diff and a list of questions that can be answered from source. It should identify the current checkout boundary and instrumentation before adding another copy of either.
A usable answer names the exact event that records success, the source of the stable identifier, and the place where the user can first receive either experience. “Order created” may fire when payment is still pending. “Payment button clicked” can fire before validation fails. If your business definition requires successful payment, use the event your order system records once that state is true. Get agreement from the owner of the checkout metric before wiring it into a result.
Put boundaries on identity, time, and display
An account may belong to several people and a shopper may use more than one device. This example assumes an authenticated user is the unit whose assignment you can reconnect to an order. If your checkout allows guests, decide whether those guests are eligible and whether an order created after sign-in can be joined back to the original assignment. A missing guest-to-user mapping cannot be fixed by renaming a field in the experiment specification. Either repair the identity chain or narrow eligibility to the flow where it works.
Use the first eligible assignment as the start of the seven-day observation window. A second render from the same user on day six does not restart the clock. Pick an explicit endpoint for events exactly on the boundary and apply the same rule to both groups. Record a qualifying outcome once per assigned user even when the user purchases twice. Keep the underlying orders for troubleshooting, but make the reported proportion match the behavioral question in the brief.
A final decision also needs a measure of practical value. The example deliberately leaves the minimum useful improvement open, because it depends on the volume of eligible checkouts, contribution margin, support costs, and opportunity cost in your product. Write yours down before reading live results. Keep one reliability measure, such as payment errors among eligible checkouts, alongside it. A copy edit should leave the payment system alone. A jump in errors is a reason to inspect the implementation immediately.
Give Claude Code a checkout change it can verify locally
Begin in a scratch directory or a clean branch of the application. If Claude Code is new to your machine, follow the terminal quickstart for installation and sign-in. Keep the boundary between the tools clear. Your Claude Code session requires access to Anthropic or a supported provider. The local GrowthBook example below evaluates an experiment payload without a GrowthBook account, SDK key, or network call. Package installation requires access to the npm registry.
For a standalone implementation, create an empty directory and install the SDK version used for this example. The commands assume Node.js 22 or later and npm. An existing application can use its own package manager and lockfile. Run this version of the setup in a new directory to avoid changing an application's current dependency graph during the walkthrough.
The Claude Code CLI starts an interactive planning session with the last command. Give the agent the decision and the invariants the implementation needs to preserve. In a new directory, the agent can propose the standalone files below. In an existing application, its first job is to find the real rendering and identity boundaries. A small experiment is a good reason to reuse the existing checkout tests.
Review the plan for a subtle error. An assistant may propose assigning a fresh random number every time the component renders. That would allow the same shopper to see both headings on successive visits. Another plausible plan always renders the new heading for signed-in customers. That checks a targeting rule, but it gives the comparison no randomized control. Ask for a stable identifier, distinct boolean values, and a test that exercises the SDK's experiment rule. When the plan matches the decision, use Claude Code's permission controls to allow local edits, or copy the files directly.
Load a fixture through the SDK
Create checkout.mjs with the following contents. The GrowthBook Node.js SDK accepts a local payload through synchronous initialization. Define the existing experience as the feature default. Give the experiment rule two variations, equal weights, and a stable hash attribute. An eligible ID can then enter a repeatable allocation. A caller with no ID has a valid existing heading to render.
The rule key identifies the local experiment and matches the flag key here. The ordered list of variations maps index 0 to the control value and index 1 to the treatment value. The explicit boolean check also keeps a missing feature value on the existing text. The source and variation index accompany the heading so a test can tell which path produced it. A real checkout could render the heading and direct those diagnostic fields to an appropriate development log.
Keep one client per process in a running server, with a fresh context for each request. Mutating shared identity on a global client can give one request the attributes of another. The small function above passes its attributes to the evaluation call. Both callers can share the same definitions while each decision uses the correct shopper. For an actual application, obtain its identifier from the same identity system used to join the eventual purchase to the exposure. The example's synthetic string stands in for that identifier.
Create demo.mjs in the same directory. This file exercises the rule, prints one result, and releases the client. It helps another engineer reproduce the decision without running a full checkout, opening a warehouse, or initiating a purchase.
Run the demo twice with the same ID. The specified SDK, rule, and ID yield the same heading both times.
The source field is important. A shopper legitimately assigned to the control sees the same text as a shopper who could not join the experiment. Only one of those decisions belongs in a randomized comparison. A screenshot cannot distinguish them. If the heading matches but the source reads defaultValue, inspect the payload, the spelled key, and the identifier before investigating the measurement pipeline.
Verify rendering and assignment as separate behaviors
Create checkout.test.mjs next to the other two files. These tests use the built-in Node.js test runner. The forced rule in the second test is confined to that newly created fixture client. It proves a known input can render each heading. The final test uses the two-variation rule itself, with a new client to approximate a process restart.
Run the tests and demo from the same directory. In an existing repository, also run its native checkout or component tests to catch changes in the real page. When a teammate or CI runner checks out the standalone example with its lockfile, npm ci can restore the recorded dependency tree.
Expect three passing tests. The 100 synthetic identifiers should exercise both branches. An exactly 50/50 count across that small list is unnecessary, and a test that demands it can fail with a correctly weighted rule. The repeated user must get the same assignment across clients initialized with the same configuration. If that fails, ask Claude to identify which inputs influence the SDK's decision before changing the test. The GrowthBook SDK specification documents the experiment fields and bucketing behavior.
Try the local flag workflow
Use the TypeScript guide to put flag evaluation in your codebase and verify the behavior before connecting a demo project.
Open the Local Flags GuideHave Claude adapt the fixture to the actual checkout
The example makes the decision inside a small function so the implementation is easy to inspect. In a production codebase, direct Claude to the component that already owns the heading and the application-level code that already supplies feature definitions. Keeping those two responsibilities separate makes it possible to review the product change independently from how the experiment reaches a client. Ask for a patch that another engineer can compare with the three tests.
Inspect the diff before accepting a green test run as evidence about your UI. Did the component actually use the selected text? Does an error state accidentally evaluate the experiment while the checkout is unavailable? Does changing the flag alter the order value, submission handler, or tracking event? A narrow text experiment should leave those behaviors stable. Exercise both headings at a narrow viewport and with a long order total. A successful unit test cannot tell you if the treatment wraps over a payment control.
The runnable fixture establishes a local baseline, including a real SDK allocation and controlled checks of the two render branches. It creates no managed experiment record. It also sends no exposure or purchase event. For the connected experiment, keep a short record of the differences to check against the draft, including the key, variation order, randomization unit, entry point, and fallback. A dashboard using treatment as variation 0 could invert your interpretation even when every local rendering test passes.
Capture one assignment before wiring an analytics destination
Save receipt.mjs alongside the files from the local checkout example. This uses the same installed SDK, the same flag definition, and the same user as the rendering test. The callback writes to an in-memory array, so you can inspect a real SDK assignment without sending events to a live analytics system.
Run node receipt.mjs from that directory. Expect one JSON object with user_id equal to demo-user-17, experiment_id equal to checkout-summary, and variation_id equal to the string "0". The timestamp reflects when you ran it. That last distinction matters when you compare the example with the fixed historical timestamps in the SQL fixture. Its dates make the expected seven-day result reproducible.
An empty array is actionable. Check that the feature actually ran an experiment rule, that the nonempty id reached evaluation, and that the callback was attached before the feature was read. An event with the right flag name but the wrong user identifier points to a different problem. Follow the evaluation-time attributes through the callback. Reading a mutable global account after the render has finished can attach a later account to an earlier decision.
In an application integration, replace the array with your existing event transport, preserving the occurrence timestamp if delivery is delayed. Keep QA in its own environment or clearly marked stream. Verify one synthetic event entered the expected test destination before allowing a production readout to depend on that path. This local callback demonstrates the shape produced by the SDK. The next check establishes what the warehouse does with that shape.
Save a draft that matches the code
A local test can show that the two checkout summaries render. GrowthBook needs a second set of facts before it can measure them. Which project owns the experiment? Which warehouse table records exposure? Does the identifier on that table mean the same thing as the application's user ID? Two data sources can both have a metric named “completed checkout” and answer different questions. Have Claude resolve those references before allowing it to save a draft.
Use a demo GrowthBook project where you can create experiments. The official GrowthBook agent skills include a read-only experiment design workflow and a separate launch workflow. In Claude Code the domain command is /growthbook:experiments. A reference workflow name such as experiment-design is an instruction for the skill to follow. If you have it installed, enter the domain command and give it this request:
The local fixture doesn't create the remote flag. If discovery finds no match, you can prepare it in the demo project with the official /growthbook:feature-flags skill. Substitute the project ID you just inspected and ask for this limited change:
If the key exists in a different project or has a different type, choose another demo project or resolve the conflict with its owner. For a newly created flag, the read-back should show the intended project, the control default, and no experiment rule. Run the read-only design request again with that known key.
Compare the returned identifiers with the tracking code. In this example the SDK sets the attribute named id to a stable value such as demo-user-17. The assignment query must understand that identifier type, and the checkout event must be joinable to it. A metric measured per browser session, or a query that only knows an anonymous device ID, needs a different design. Record how many days an assigned person has to complete checkout and what starts that clock. A seven-day filter on a dashboard is a moving calendar range and won't by itself implement a seven-day post-assignment conversion window.
Review the experiment payload before a write
The standard experiment launch workflow distinguishes the experiment record from the feature rule that serves its variations. An experiment without a template takes explicit data source and assignment query IDs. The tracking key connects the exposure event to this experiment. The variation keys identify the arms. The boolean values returned to the app belong in the flag rule.
For the explicit, no-template path, save the following as checkout-draft.json in a scratch directory. Replace every placeholder with the corresponding ID returned in discovery. The guardrail needs a real matching metric. If your project has no suitable one, resolve the design with the metric owner before trying this configuration.
The next two snippets use a POSIX shell, curl, and jq. Provide GB_API_KEY to that shell through your normal secret-management mechanism. The skills' setup file and your shell environment are separate. Use a scoped management token as described in the GrowthBook API authentication guide. The application's client SDK key serves a different purpose. The origin below is for GrowthBook Cloud. Supply the API origin for your own installation if you self-host.
After reviewing the JSON and checking that the project has no existing experiment for this pilot, explicitly create the demo draft once:
A successful creation returns the experiment ID and server-generated variation IDs. Read them from the saved response. If a network connection drops after you submit the request, search the demo project for the experiment before retrying. A lost response doesn't establish whether the server saved the draft. An authentication error calls for checking the origin and token, while an invalid metric or assignment query calls for returning to discovery.
Read the record back independently and check the fields against the file you submitted:
Expect a draft, the matching tracking key, and two arms in the agreed order. Compare their IDs with the creation response before mapping the control ID to false and the treatment ID to true on a feature draft. A missing record, an unexpected status, or a reused key attached to another test deserves investigation. A JSON file on disk is a request you intended to send. This fetched record tells you what the project actually contains.
The later launch steps attach an experiment-reference rule to a feature revision, review the target environment and traffic split, and start the experiment. The start operation can publish the linked rule. Stop at the draft read-back while someone is still reviewing copy, verifying events, or checking that the two arms are equally eligible. A saved design and an application that can render both branches give that reviewer something concrete to inspect before customers enter the test.
Follow the assignment into a completed checkout
The revised summary can render correctly while the experiment still produces unusable data. A developer might call the SDK when the homepage loads, then treat every visitor as someone who reached checkout. Or the order service might store a billing account ID while the frontend assigns by user ID. Ask Claude Code to trace one user from evaluation through the assignment query to a settled outcome. Give it a precise expected result before asking it to write the query.
For this test, evaluate checkout-summary when an eligible user reaches the decision that selects the summary text. The control flag value is false and the revised text is true. A variant's boolean value controls rendering. The assignment event carries the experiment and variation tracking keys. In this fixture the experiment key is also checkout-summary, and variation keys 0 and 1 map to control and revised respectively. Confirm the actual keys in your own experiment rule. A feature key and its experiment tracking key can differ.
Check the SDK callback against the assignment table
In the GrowthBook JavaScript SDK's tracking callback, the first argument supplies experiment.key and the second supplies result.key. The current SDK example sends those as experimentId and variationId. The third argument supplies the evaluation-time user context in supported SDK versions. If the bucketing attribute is id, use that stable identifier from the evaluation context when constructing your analytics event. Include only the fields you need for this analysis. The pipeline's source timestamp becomes the assignment time. GrowthBook's experiment assignment queries read the participant identifier, timestamp, experiment ID, and variation ID from your data source.
Look at one emitted event for demo-user-17 before moving on. Read the key, variation, identifier, and time from the event your instrumentation actually produced. Match them against the warehouse projection. If your analytics SDK automatically adds its own anonymous identifier, verify which column ultimately feeds the experiment. An event named “Experiment Viewed” can be present and healthy in a debugger while the assignment query returns zero rows for the signed-in user.
For the outcome, use the order service's durable completion event. Record both the order ID and user ID so you can identify retried deliveries and attribute the purchase. A page impression on a confirmation route makes a poor substitute if a browser refresh emits it twice. If a payment processor drives your outcome, its documentation may already describe how to recognize duplicate webhook deliveries. Use source occurrence times for the conversion window and track arrival time independently to diagnose lag. OpenTelemetry distinguishes those two timestamps.
Run a seven-day conversion check with synthetic rows
Save the following as checkout-check.sql. The data are synthetic and the tables are temporary. The query takes one row per assigned user and gives each user at most one conversion. The interval includes assignment and ends just before the same time seven days later. This reproduces the metric contract for this exercise. Adapt the boundaries to match the actual configured metric before comparing its output with GrowthBook.
With Python 3 installed, run the two queries directly against an in-memory SQLite database. Save this runner as run-check.py beside the SQL file, then run python run-check.py. It returns a nonzero status if the fixture yields a conflicting assignment or the totals change. The SQL uses the documented SQLite date and time modifiers. All timestamps in this example share a UTC representation and fixed precision, which makes the comparisons unambiguous.
Ask the agent to explain each excluded event
The revised summary has one mature participant and no qualifying order. Its completed checkout occurred exactly at the end of the seven-day interval. Control has two mature participants and one conversion. The second evaluation for demo-user-17 doesn't restart the clock. Its duplicate order delivery doesn't create a second converted user. The order for case-no-order predates assignment. The last participant, case-recent, has had only a little over one day of follow-up as of the fixed analysis time.
That last case illustrates right censoring. A person with six days to go may yet complete checkout. For this fixed-window reconciliation, leave them out of the mature-cohort denominator and count them separately as pending. Move the analysis time forward a week and rerun. The revised summary now has two eligible users, so the runner should fail until you update the expected total. If you run the same comparison on real events, account for the ingestion delay as well. Seven elapsed days on the clock cannot guarantee that every event has reached the warehouse.
Next, change the second demo-user-17 exposure to variation 1 and rerun the original observation cutoff. The conflict query should name that user, and the runner should stop. Choosing the smallest variation key would quietly assign a crossover user to control. Investigate the experiment configuration, evaluation-time ID, and any forced variations before adopting a policy for real crossovers. The fixture's exclusion makes the discrepancy visible. A production analysis needs to document how the policy affects its population.
Keep the three kinds of evidence distinct
Passing this fixture demonstrates that local SQL can recover the stated counts from known inputs. An authenticated project read can verify which experiment key, variation keys, assignment query, and goal metric are configured. A draft in a dedicated demo project can establish that the objects are linked before anyone launches traffic. Only observed test events traversing the actual SDK, collector, and connected warehouse verify delivery through that path. Use a designated test context and keep its records out of the production readout.
Ask Claude Code for the evidence needed at each step in plain language. A useful local receipt includes the test command and its output. A project-inspection receipt records the project and experiment IDs, observation time, and metric window. An integration receipt pairs one test exposure with its matching warehouse row and outcome. If the authenticated read or ingestion check never happened, record the outstanding step alongside the passing fixture so the next engineer knows exactly what to verify.
Decide what qualifies the draft for real traffic
Bring three artifacts to the release review. The first is a reviewed code change showing the old and revised text and their shared decision point. The second is a small set of synthetic rows with expected results computed independently of the UI. The third is the demo-project read-back showing which flag, metrics, variations, and assignment unit the draft actually references. A passing rendering test covers only the first item. A plausible chart from fabricated rows covers only the second.
Ask a teammate who did not write the prompts to run the local tests, explain why one incomplete checkout remains in the denominator, and read the experiment configuration back from its owning system. In the code review, search for a consumer of the flag that might evaluate it before the shopper reaches checkout. In the data review, search for a filter on a post-assignment event that one variation changes. Those are small mistakes that can survive both a well-written prompt and a green build.
When a separate release decision comes, use the experiment lifecycle to connect ownership, launch, analysis, and eventual cleanup. Keep test users and forced previews distinguishable from actual participants. Watch for assignment or telemetry failures during rollout. When enough eligible users have had seven days to convert, read the estimate against the original decision threshold and guardrails. An agent can assemble the readout. The evidence it should use is the agreed metric and the experience that real eligible shoppers actually received.
Inspect the experiment design skill
Open the GrowthBook workflow for turning a hypothesis and a metric into a draft you can review with your team.
Read the Design WorkflowRelated 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.



