Experiments

Best product analytics tools for product teams

A graphic of a bar chart with an arrow pointing upward.

On Monday, the onboarding team celebrates a jump in activation. On Tuesday, customer success asks why so many new accounts still need help creating their first project. Both teams can be right. The dashboard counts people who clicked “Create project.” Customer success counts workspaces that saved a project and had someone return to use it. Buying a better chart won't settle which outcome deserves the name.

The best product analytics tools let a product manager, designer, and analyst work through that disagreement while the decision is still on the table. A designer may need to see what happened before an abandoned click. An analyst may need to match an event to a billing record. A PM needs to know which customers would benefit from a change and how to tell whether it helped. Those are different jobs. Start with the one that regularly slows your team down.

Five product analytics tools worth a closer look

ToolPut it on the shortlist whenAsk for this in the trial
GrowthBookYour warehouse holds the outcome data, and product managers use experiments to make release decisions.Explore an existing KPI, then use the same metric definition to evaluate a change.
AmplitudeProduct analysts and PMs regularly compare behavior across cohorts and need to share those investigations.Build a retention cohort and have a second PM explain exactly who qualifies.
MixpanelPMs want to answer follow-up questions about conversion and repeat usage in event-based reports.Break down a familiar funnel and reconcile one surprising segment with individual events.
HeapThe team often thinks of a question after a change has shipped and needs to examine previously captured interactions.Define an old interaction and test whether its label still describes what happens in the current interface.
PostHogProduct and engineering investigate releases together and want to move from an aggregate change to a recorded session.Follow a checkout drop-off to a session, then reconcile the outcome with the order record.

What does the team need to decide?

Pick one upcoming decision with a real owner. “Should we move the invitation step until after the first project is saved?” works well. “We need better activation analytics” allows every vendor to demonstrate its strongest chart. Write down what evidence would change the owner's mind. If nobody can name it, the trial needs a narrower question.

Separate the customer's goal from the signal you can observe

Have a PM and a designer finish the sentence “A new customer gets value when…” independently. Compare their answers with the event that currently represents activation. A saved project may be enough for a solo design tool. For a collaboration product, the first review from a teammate may be the first useful outcome. Google's HEART research describes a process for translating user goals into observable metrics. One benefit of doing this before a demo is that it gives the team permission to reject an easy-to-measure event.

Ask the analyst to specify the grain of the underlying data. Is there one row for every invitation sent, every unique invitee, or every workspace that sent its first invitation? Imagine that one manager sends ten invitations to the same colleague. There's one potential collaborator and one potential activated account. A count of ten might be useful to someone debugging email delivery. It would be a poor basis for expanding the invitation feature.

Give a PM a second question to answer alone

Product analytics earns its keep after the first chart has been built. Let an analyst create the initial view, then have a PM investigate why one segment is behaving differently. Can they change the date range without excluding late conversions? Can they tell whether “plan” means the plan at signup or the plan the customer has today? Have the PM write a two-sentence interpretation and show it to someone who missed the demo. A chart that survives that handoff stands a better chance of surviving a roadmap meeting.

Put one deliberately young cohort on the screen. If activation allows seven days, yesterday's signups have six more days to qualify. A tool that makes the two cohorts easy to compare can still encourage an unfair comparison. Ask the PM to restrict the view to customers with a complete observation window. Give credit for being able to explain the exclusion as well as for getting the right number.

Keep one decision from the trial as a record. Include the question, the cohort dates, the unit, and the person who can change the definition. In a month, a new PM should be able to tell whether an apparent improvement reflects a different product experience or a revised measure of success.

GrowthBook for warehouse metrics and product experiments

Where it fits

GrowthBook is the strongest fit here for a team whose analyst already trusts the warehouse and whose PM wants to test the next product change against those same numbers. GrowthBook Product Analytics can chart a defined metric, aggregate a fact table, or explore timestamped warehouse data. A team that already runs GrowthBook experiments can reuse its existing metric definitions. That saves the analyst from maintaining a dashboard version of activation and a second version for the experiment readout.

Consider a team deciding whether to provide a sample dataset during onboarding. Set up the initial exploration around one question. Of the new workspaces that imported data, how many had a second member use the result within seven days? Use a known warehouse calculation for comparison. Where the totals differ, inspect workspace identifiers, late events, and internal accounts together. That conversation gives the PM a better understanding of the metric than a perfect demo using someone else's sample data.

What the experiment adds

A low rate of second-member activity gives the team a place to investigate. It could reflect a confusing invitation step, a customer mix with more solo users, or a workflow that takes longer than a week. After reviewing those possibilities, the team can run a controlled experiment offering the sample dataset to eligible new workspaces. Random assignment gives the team a basis for estimating the change's effect on customer behavior. Use an outcome that both variants can achieve, including customers who choose to bring their own data.

If the PM wants to know where the treatment helped, GrowthBook's experiment funnel metrics can show ordered steps by variation. Read the denominator carefully. If 100 exposed workspaces start a variation, 40 import data, and 20 have a second active member in sequence, the final step reports 20% of exposed workspaces. The 50% progression from import to second member answers a separate diagnostic question. Funnel metrics require a supported source and a shared identifier between the assignment data and each step. They are available on Pro and Enterprise Cloud, and on Enterprise for self-hosted deployments.

What to check before buying

The benefit depends on the information your team can bring to the analysis. If the warehouse contains signups and invoices but nothing about the first successful project, someone still needs to instrument or model that outcome. Ask the analyst to show a valid row and a near miss before assigning the metric a prominent spot on the dashboard. Give the PM enough access to answer follow-up questions, then check the same chart from an ordinary teammate's account.

Manual metric, fact table, and data source explorations are available on all plans. The Product Analytics documentation covers explorers and dashboards. Current dashboard sharing and permissions allow Pro and Enterprise organizations to publish dashboards for organization-wide viewing, subject to access. The pricing comparison lists Cloud Pro at $40 per seat per month. Estimate the seats needed by the people doing the work, along with the underlying warehouse queries. A team that already maintains the relevant models starts this comparison in a different place from one that still needs its first reliable product events.

Choose a KPI for the pilot

Pick an outcome your team can reuse when an onboarding question turns into an A/B test. The playbook explains how to choose a primary metric and guardrails.

Read the KPI Playbook

Amplitude for teams investigating retention

Where it fits

Amplitude deserves a spot on your shortlist when several product managers need to investigate repeat behavior. Consider a scheduling app whose headline metric is weekly active users. Its growth team wants to know whether new customers return to book again. Its support team wants to know how often people reopen the app to fix a failed booking. Both actions increase weekly activity. They imply very different priorities for the roadmap. A PM who can separate those journeys during a planning meeting has a better chance of picking the right problem.

The useful question for your trial is whether somebody who didn't instrument the feature can reproduce the analysis. Give two PMs the names of the booking events, the time zone, and access to the same project. Ask each to find the share of first-time bookers who complete a second booking during the following week. Have them exchange charts and explain why the numbers agree or differ. You'll learn which chart settings need a shared default and which event definitions need an owner.

A retention chart worth building in the trial

Amplitude lets you distinguish a return during a particular interval from a return at any point after it. Suppose 100 first-time bookers have each had 28 days of follow-up. Twenty made a second booking on day seven. Another 15 skipped day seven and made a second booking later in the observation period. Exact day-seven retention is 20%. Day-seven-or-later retention is 35%. A team assessing a weekly reminder may care about punctual returns. A team trying to turn one-off purchases into repeat business may care more about the second figure.

Run the chart both ways and ask which product decision changes. Then test a booking at 11:55 p.m. followed by another at 12:05 a.m. The two events fall on separate local calendar days but fit inside ten elapsed minutes. Amplitude supports calendar dates and rolling 24-hour windows. Anyone comparing the chart to warehouse SQL needs to use the same boundary. BigQuery, for example, lets you specify a time zone when truncating timestamps.

Where teams can get a convincing but wrong answer

Define what counts as a booking carefully. A customer can tap Confirm, receive a payment decline, and reopen the app the next morning. If the chart uses the tap as its starting event and any app open as its return event, a failed transaction can appear as a retained customer. Ask the payments team for the event that marks a committed booking. Keep the tap available for diagnosing the checkout screen. Document the difference where the PM chooses events.

Inspect a few recent cohorts separately before comparing release weeks. Someone who joined yesterday hasn't had a chance to book again on day seven. For a day-seven-or-later comparison, give the older and newer cohorts the same follow-up period. Otherwise the older group has more opportunities to return even if the booking experience performed identically.

Pricing and implementation

Amplitude's public plans list 2 million monthly events on Free, behavioral cohorts and custom formulas on Plus, and custom pricing on Growth. Build an estimate from the actions your team intends to send. For a hypothetical 30,000 monthly users, a shift from 40 to 80 recorded actions per user takes you from 1.2 million to 2.4 million monthly events at the same audience size. A pilot that tracks only completed bookings can understate the cost once search and checkout events go live. Ask for the allowance and retention period on the plan you'll actually use.

Mixpanel for teams diagnosing conversion funnels

Where it fits

Mixpanel is worth evaluating when a PM regularly needs to explain where users abandon a transaction. Think of a marketplace that receives plenty of quote requests but few accepted jobs. The PM can frame the problem as a sequence of actions. A buyer requests a quote, opens a seller's reply, and accepts the quote. The result points the team toward a specific investigation. A large drop before opening the reply warrants a look at notification delivery. A drop after opening warrants a closer look at price, timing, and availability.

Give the PM one real product question and a short list of events to start with. A meaningful trial ends with a change in the team's understanding. Perhaps quotes accepted on desktop began on mobile. Perhaps a seller's response arrived days after the buyer needed the work. Each finding suggests a different fix and a different set of users to interview.

How to test whether a funnel follows the same transaction

One buyer can request quotes for both plumbing and painting. If they open the painting quote and accept the plumbing quote, a funnel that follows only the person can join those steps. Mixpanel's funnel controls let you require the same property value at every step. Send the quote identifier on the request, open, and acceptance events. Hold it constant and inspect the difference. A shrinking funnel tells you how often the broader definition let a buyer's activity on one quote satisfy a step for another.

Test three known histories. Include a buyer who completed one quote, a buyer who switched quotes midstream, and a buyer who opened a help article between opening and accepting the same quote. Under a specific-order funnel that holds the quote ID constant, the first and third histories should convert. The second should drop out. If all three convert, the property restriction deserves a second look. If the third drops out, inspect the event values and ordering. The exercise gives the PM and engineer a shared test they can run after an instrumentation change.

What to check before diagnosing a drop

Spot-check the handoff between client and server. A click records intent. The marketplace's transaction ledger records whether the seller actually got the job. Keep an identifier you can use to reconcile the accepted quote on both sides. If a pipeline derives the final event from a payment webhook, plan for a retry. Stripe, for example, documents how to recognize duplicate webhook deliveries. One buyer's duplicate acceptance may leave a unique-user conversion rate unchanged while inflating a report that totals completed jobs.

Ask your engineer where the quote ID lives. Someone who requests ten quotes has ten relevant identifiers. The identifier belongs with each action. A user profile field holding the latest quote can overwrite the context of earlier activity. This is the distinction behind the event name and properties in a tracking call. Store a stable ID on each step and reserve display labels for the words a user would recognize.

Pricing and implementation

Mixpanel's plan comparison lists up to 1 million monthly events on Free. Its paid plans offer Group Analytics as an add-on. That matters if one person requests a quote but another accepts it on behalf of the same company. Bring that case to the trial and ask to see an account-level result on the proposed package. Also estimate the cost of importing events from the warehouse. Mixpanel counts events sent through its warehouse connectors toward the event limit. Put a normal month, a seasonal peak, and any planned historical import on separate lines when requesting a quote.

Heap for questions that surface after a release

Where it fits

Your onboarding survey says people can't find the option to import a file. The team remembers shipping the button. Nobody remembers adding a tracking event for it. Heap is worth a look if this kind of question routinely lands on a PM's desk. Its autocaptured interaction data includes web pageviews, clicks, form submissions, and changes to form controls. Within the history you've retained, you can define a past interaction using the attributes you collected at the time.

That changes what you can do in the next planning meeting. A PM can check whether people opened the import dialog before making the case for a redesign. A designer can ask whether the old navigation exposed the entry point more often. For either question, the app had to be sending the relevant data before the release. A missing backend record still calls for a different investigation.

What to try with the team

Ask someone who knows the product to define “opened the file importer” on yesterday's traffic. Give them two examples. In one, a user opens the dialog from an empty project. In the other, the user clicks “Import” inside an existing project. Decide whether both belong in the count. Heap's visual event labeling lets you inspect the elements a definition selects and narrow it by URL or text.

Now have a second person open the dialog from both entry points. Try the keyboard shortcut, the localized version, and the cancel button in the dialog. Inspect which actions meet the definition. Those five minutes can reveal that a perfectly sensible chart name describes only the English-language button. If engineering owns the component, an explicit HTML data attribute can give the team a stable identifier through a copy change. Decide who will maintain it when the component is replaced.

Where the history runs out

A click can show intent. It takes a different event to establish that a file was successfully parsed, or that the first row made it into the customer's project. Count dialog opens, upload attempts, and completed imports separately. A browser can fire a form submission when someone presses Enter, and the server can still reject the file. An engineer should supply the accepted-import record if that outcome drives the activation metric.

A useful trial deliberately includes one invalid file and one duplicate. If your chart marks all three files as successful, its name promises more than its underlying event delivers. Giving that chart a more accurate name, such as “submitted import form,” preserves the discovery work while the team adds the missing completion event.

Keep the failed file in the test cases for the next release. If the import dialog moves and successful imports suddenly fall to zero in the chart, replaying that case can help you locate the broken definition before a team spends its planning meeting debating a product change.

What drives the quote

Heap lists a free tier of up to 10,000 monthly sessions with six months of history. Pro and Premier use custom session pricing. Heap Connect, which syncs data to your warehouse, is an add-on for Pro and included with Premier. Ask for an estimate using the sessions generated by your web and mobile clients. Heap defines their inactivity windows differently, so a forecast based on visitors or sign-ins can miss a meaningful share of usage. If annual seasonality is central to the question, include enough retained history for the comparison in the quote.

PostHog for teams investigating a release together

Where it fits

A PM sees a drop in checkout completion after a release. The engineer who shipped it wants the affected version, the sequence of actions, and a recording that demonstrates the problem. PostHog is a good candidate when that handoff is frequent. Its product analytics and session replay share event and person context. The same team can build a funnel, investigate a session behind it, then decide what additional evidence would distinguish an instrumentation change from a regression.

Use a small, familiar flow to evaluate the handoff. Suppose checkout starts on the web, then a payment provider takes over. Agree in advance that a confirmed payment counts as success even when the buyer closes the tab before returning to the store. For a Stripe integration, for example, checkout fulfillment can proceed after a buyer leaves. A return-page view answers a different question. That distinction matters more to the roadmap decision than the number of available chart types.

What to try with the team

Have a PM build the checkout funnel and an engineer independently count the same paid orders. Give them a short list of order IDs for matched and unmatched cases. For one checkout that appears to have failed, follow the events and, where captured, the recording. A disabled submit button is actionable. A missing recording needs another source of evidence. For a checkout that appears twice, compare order IDs before counting two purchases. Check the delivery history for a payment notification that the provider retried.

Then ask the PM to hand the saved analysis to support. Can a support engineer identify which app version the affected customer used and whether that customer eventually completed payment? One replay can illustrate why a person abandoned the flow. The team still needs a defined population and a rate to estimate how widespread the issue is.

Watch the account boundary

For a B2B product, give one person access to two test workspaces. Have that person create a project in the first and invite a colleague in the second. If activation requires both steps in the same workspace, neither workspace has activated. In PostHog, group analytics associates events with groups. Attach the active workspace to each relevant event and inspect the resulting group funnel. A person-level funnel could show a conversion even when the product team's account-level condition was never met.

What drives the bill

PostHog's product analytics pricing includes the first million captured events per month and charges for additional volume. Estimate from a representative week and split out automatic interactions, deliberate product events, and backend activity. Check how many events have identified profiles. Group analytics is a paid add-on whose billing covers all identified events in the project once enabled, including identified events with no group attached.

Run that forecast again for a busier release week. A checkout redesign can create more interactions per buyer even when traffic stays flat. Have the budget owner price the event mix and the additional products the team will use. That gives the team a fair comparison with a session-based quote and a reason to review collection when it adds a high-volume interaction.

Give the finalists one question your team has to answer

Choose a decision someone will make in the next month. A collaboration product might have one onboarding sprint available. The PM needs to decide whether to help workspace owners invite colleagues or help invited colleagues finish their first shared task. A polished activation dashboard can hide the difference. Twelve invitations might come from a single enthusiastic owner. The unit for this decision is a new workspace, and the next question is what happened inside each one.

Give each finalist the same slice of data and the same question. Include a small set of fictional workspaces with known histories alongside the larger sample. Let the data team keep the expected results until the PM has worked through the analysis. A ten-minute vendor demonstration can show how to draw a funnel. The pilot should tell you who can explain the number on Monday, who can fix it on Tuesday, and whether the fix reaches the report everyone uses on Wednesday.

Count the workspaces by hand once

Suppose 100 eligible workspaces were created in a week. Within 7 days, 60 invited a colleague and 24 of those had an invited colleague complete a shared task after the invitation. Your workspace activation rate is 24%. Among workspaces that invited someone, the completion rate is 40%. Forty workspaces never issued an invitation. Another 36 invited someone and stalled. Those populations need different product changes, even though both look like a drop in the activation funnel.

Now add three awkward records. An owner works in two workspaces. A colleague accepts an invitation on a phone and completes the task on a laptop. A mobile client queues a completion that happened on day 6 and delivers it on day 8. Ask the PM to open each history and identify the workspace that should get credit. Can they tell which timestamp controls the window? The distinction between when an event occurred and when a collector saw it gives engineering two fields to compare when a late delivery moves the chart.

Send the same completion twice with its original identifier. The CloudEvents convention for identifying duplicate events pairs an event source with its event ID. Use the corresponding identifiers in your own pipeline to follow the retry. A unique-workspace count might stay at 24 even if the platform counts both deliveries. Open a total-completions chart too. You want to learn whether deduplication happens at collection, inside selected reports, or in the warehouse model your analyst maintains.

Make retention answer a second question

Ask how many activated workspaces complete another shared task in the second week after creation. Define that interval as elapsed days 7 through 13, with the end boundary at day 14. If 9 of the 24 activated workspaces return during that interval, retention among activated workspaces is 37.5%. Express the same 9 as a share of all 100 new workspaces and you get 9%. Label the denominator before sharing either figure. A teammate opening the chart next quarter should know which question it answers.

Pick a creation cohort old enough to have finished the entire observation window. Add a younger cohort and see what the tool displays for a week that has yet to finish. Also ask the PM to switch from a workspace returning in that specific week to a workspace returning at any point from day 7 onward. One workspace that comes back on day 17 is enough to show whether the chart supports the intended definition. Save the chart, share it with a colleague, and have them explain the settings from the report they receive.

Test who can use the report and what data it exposes

Give the designer ordinary viewer access. Have them open the shared report, read the two segment values, and change the date filter using a keyboard. A chart that communicates its meaning only through a hover tooltip may leave a member of the review meeting dependent on a colleague. Look for keyboard access to the controls and a text description or data table that conveys the chart's information. Try the shared version too. The editor and the published report can present different controls.

For privacy review, create a fictional workspace with a distinctive project title and a test email address. Neither field is necessary to count a completed task. Keep the workspace ID, event type, and timestamps, then inspect the actual event payload, exported rows, and a session recording if replay is part of the evaluation. Data minimization and purpose limitation give the reviewer a concrete question for each field. What decision requires it? Record which restriction acts before collection and which one only limits who can see a stored value. Repeat the inspection after the next SDK configuration change.

Rebuild one chart from an export

Ask an analyst who didn't set up the trial to recreate the activation figure in your warehouse. Give them the exported events, the identity mapping they're allowed to use, and the saved metric definition. Have them find the person who changed devices and the owner who belongs to two workspaces. If the exported rows preserve an opaque profile identifier and the mapping is missing, count the hours and extra tooling needed to recover those journeys. Keep a list of definitions, cohorts, and permissions someone would have to recreate by hand.

Then introduce a small instrumentation change. Rename a property in a test release and send a completion with the workspace ID missing. Check whether anyone sees the error before the weekly report goes out. An analyst who owns ingestion can use JSON Schema's required properties and object validation to catch an absent field. A PM still needs to know who receives that alert, which previous rows need repair, and when the corrected count will appear in a saved report.

Price the working configuration

Build a workbook from one representative month. Suppose 40,000 people generate 2.4 million events, 14 colleagues need editing access, and the data team expects to retain 13 months of history for year-over-year comparisons. Create a row for each billable unit. Fill in the quantities the vendor would actually count, the included allowance, any commitment, the next volume tier, and the price of export, identity features, or longer retention where those carry a separate charge. Use the quote for the configuration that passed the pilot.

Run two forecasts. In the first, the same 40,000 people generate 50% more events after a new feature ships. Volume rises to 3.6 million events while the number of people stays constant. In the second, a regional launch grows the audience to 60,000 while events per person stay at 60. Volume again reaches 3.6 million. An event-metered plan sees similar demand in both scenarios. A plan metered by tracked people can produce two different bills. Recalculate using the vendor's treatment of anonymous visitors if those visitors appear before sign-in.

Give warehouse compute and staff time their own lines. For BigQuery on demand, for example, you can estimate data processed and set a maximum bytes-billed limit for representative queries. Record how often the dashboard refreshes and whether several viewers trigger additional queries. To compare options, divide the same total monthly cost by a business unit the team recognizes, such as active workspaces. That follows the FinOps approach to unit economics. Keep the cash estimate and the weekly maintenance hours visible as separate figures for the people accountable for each.

Score the evidence the team can reproduce

Use four scores from 0 to 2 for each finalist. Award 2 when the intended owner completes a task independently, 1 when they complete it with recurring help or a documented workaround, and 0 when the team can't obtain a trustworthy result. Score the PM's activation and retention readout, the analyst's export reconciliation, the designer's ability to use the shared report, and finance's ability to reproduce the forecast. Record a report link, query, or worksheet next to each score. Keep any mandatory privacy or access requirement as a separate pass condition.

Read the individual scores before adding them. Two products can each score 6 out of 8 while asking different people to absorb the work. One might require an analyst at every product review. Another might give the PM independence but require engineering to maintain an identity export. Put the names and estimated hours next to those obligations. The budget owner can now choose which recurring work the team can afford and which capability justifies the subscription.

Choose the tool you'll use at the next roadmap review

GrowthBook is our first choice for a product team that keeps its business metrics in a warehouse and expects to test changes against them. Think back to those 36 workspaces that sent an invitation and stalled. The PM can explore which workspaces got stuck, the designer can propose a clearer invitation, and the analyst can measure that change with the same definition of activation the team uses in its weekly review. That continuity matters when a small discrepancy in who counts as activated can change a launch decision.

Pick your other finalist around the question that consumes the most time today. If several PMs spend Monday comparing which customers return and how often, put Amplitude through the retention exercise. If the hard part is following a transaction across a marketplace, ask Mixpanel to follow one quote from request to acceptance. Heap deserves the trial when the team often discovers a question after the interface has changed. PostHog belongs on the shortlist when an engineer and a PM routinely investigate a release together and need to move between aggregate behavior and a specific session.

Before committing, bring a report your team already disagrees about. Ask the person who raised the original question to produce the answer, and the person who challenged it to check the underlying records. If warehouse access, account identity, or dashboard permissions need a closer look, bring those details to a GrowthBook demo. For a hands-on evaluation, start a GrowthBook workspace and recreate one weekly metric. You'll have a report your colleagues can challenge and a clear next product decision to make with it.

Rebuild your activation report

Connect a data source in GrowthBook and use one of your weekly metrics to try the product analytics pilot with your team.

Get Started With GrowthBook

Table of Contents

Related Articles

See All Articles
Feature Flags
Experiments

Add local feature flags to a React app with TypeScript

Nov 20, 2026
x
min read

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.

npm create vite@latest issue-shelf -- --template react-ts
cd issue-shelf
npm install
npm install @growthbook/growthbook@^2.2.0 @growthbook/growthbook-react@^2.2.0

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.

import type { LocalFeatures } from "@growthbook/growthbook";

export type Edition = "guest" | "subscriber";
type Features = { issueLimit: number };
type Attributes = { id: string; edition: Edition };

declare module "@growthbook/growthbook" {
  interface Register {
    features: Features;
    attributes: Attributes;
  }
}

export const features: LocalFeatures = {
  issueLimit: {
    defaultValue: 2,
    rules: [
      { condition: { edition: "subscriber" }, force: 4 },
    ],
  },
};

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.

import { useMemo, useState } from "react";
import { GrowthBook, GrowthBookProvider } from "@growthbook/growthbook-react";
import { features, type Edition } from "./flags";
import { IssueShelf } from "./IssueShelf";

export default function App() {
  const readerId = "reader-17";
  const [edition, setEdition] = useState<Edition>("guest");

  const gb = useMemo(() => new GrowthBook({
    attributes: { id: readerId, edition },
    defaultHashVersion: 2,
  }).initSync({ payload: { features } }), [readerId, edition]);

  return (
    <GrowthBookProvider growthbook={gb}>
      <main>
        <h1>Recent issues</h1>
        <p>Current edition: {edition}</p>
        <button onClick={() => setEdition(
          edition === "guest" ? "subscriber" : "guest"
        )}>
          Switch edition
        </button>
        <IssueShelf />
      </main>
    </GrowthBookProvider>
  );
}

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 Guide

The 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.

import { useFeatureValue } from "@growthbook/growthbook-react";

const issues = [
  { id: "nov", title: "November · Print shops" },
  { id: "oct", title: "October · Bookbinders" },
  { id: "sep", title: "September · Type designers" },
  { id: "aug", title: "August · Paper mills" },
];

export function IssueShelf() {
  const limit = useFeatureValue("issueLimit", 2);

  return (
    <ul aria-label="Recent magazine issues">
      {issues.slice(0, limit).map(issue => (
        <li key={issue.id}>{issue.title}</li>
      ))}
    </ul>
  );
}

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.

npm run build
npm run dev

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.

npm ls @growthbook/growthbook @growthbook/growthbook-react

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.

Show two public issues to guests and four to subscribers.
Keep the same reader ID when switching editions in the test.
Report the initial titles, the titles after upgrading, and the titles
after switching back. Include the type-check command you ran.

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 GrowthBook
Feature Flags
Experiments

Use local feature flags per request in Node.js

Nov 20, 2026
x
min read

Two 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.

npm init -y
npm pkg set type=module
npm install @growthbook/growthbook@^2.2.0
npm install -D typescript tsx @types/node@22

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.

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "strict": true,
    "noEmit": true,
    "skipLibCheck": true,
    "types": ["node"]
  },
  "include": ["*.ts"]
}

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.

import type { LocalFeatures } from "@growthbook/growthbook";

type Features = { includeUniqueReaders: boolean };
export type Workspace = { workspaceId: string; reportPreview: boolean };

declare module "@growthbook/growthbook" {
  interface Register {
    features: Features;
    attributes: Workspace;
  }
}

export const features: LocalFeatures = {
  includeUniqueReaders: {
    defaultValue: false,
    rules: [{ condition: { reportPreview: true }, force: true }],
  },
};

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 Guide

Create 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.

import { createServer } from "node:http";
import { setTimeout as delay } from "node:timers/promises";
import { GrowthBookClient } from "@growthbook/growthbook";
import { features, type Workspace } from "./flags.js";

const client = new GrowthBookClient({ defaultHashVersion: 2 })
  .initSync({ payload: { features } });

const demos = new Map<string, Workspace>([
  ["/demo/preview", { workspaceId: "press-a", reportPreview: true }],
  ["/demo/standard", { workspaceId: "press-b", reportPreview: false }],
]);

createServer(async (req, res) => {
  const workspace = demos.get(req.url ?? "");
  if (req.method !== "GET" || !workspace) {
    res.writeHead(404).end();
    return;
  }

  const gb = client.createScopedInstance({ attributes: workspace });
  await delay(10); // Stand-in for loading this workspace's report.
  const expanded = gb.isOn("includeUniqueReaders");
  const csv = expanded
    ? "period,downloads,unique_readers\nweek-1,80,55\n"
    : "period,downloads\nweek-1,80\n";

  res.writeHead(200, {
    "Content-Type": "text/csv; charset=utf-8",
    "Cache-Control": "private, no-store",
  });
  res.end(csv);
}).listen(4178, "127.0.0.1", () => {
  console.log("Report server listening on http://127.0.0.1:4178");
});

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.

npx tsc --noEmit
npx tsx server.ts

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.

import assert from "node:assert/strict";

async function report(name) {
  const response = await fetch("http://127.0.0.1:4178/demo/" + name);
  assert.equal(response.status, 200);
  return response.text();
}

const [preview, standard, previewAgain] = await Promise.all([
  report("preview"), report("standard"), report("preview"),
]);

assert.equal(preview, "period,downloads,unique_readers\nweek-1,80,55\n");
assert.equal(standard, "period,downloads\nweek-1,80\n");
assert.equal(previewAgain, preview);
console.log("Both workspaces received the expected CSV.");

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 GrowthBook
Feature Flags
Experiments

Use local feature flags in the Next.js App Router

Nov 20, 2026
x
min read

Your 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.

npx create-next-app@latest agenda-flags --ts --app --empty --use-npm --no-src-dir --no-tailwind --yes
cd agenda-flags
npm install @growthbook/growthbook@^2.2.0 server-only

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.

import "server-only";
import { GrowthBookClient, type LocalFeatures } from "@growthbook/growthbook";

type Features = { agendaRoomDetails: boolean };
type Attributes = { audience: "preview" | "public" };

declare module "@growthbook/growthbook" {
  interface Register {
    features: Features;
    attributes: Attributes;
  }
}

const features: LocalFeatures = {
  agendaRoomDetails: {
    defaultValue: false,
    rules: [{ condition: { audience: "preview" }, force: true }],
  },
};

const client = new GrowthBookClient({ defaultHashVersion: 2 })
  .initSync({ payload: { features } });

export function showRoomDetails(audience: Attributes["audience"]) {
  const gb = client.createScopedInstance({ attributes: { audience } });
  return gb.isOn("agendaRoomDetails");
}

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.

import { Suspense } from "react";
import { cookies } from "next/headers";
import { showRoomDetails } from "../../lib/agenda-flags";
import { Agenda } from "./Agenda";

async function AgendaForVisitor() {
  const jar = await cookies();
  const audience = jar.get("agenda-preview")?.value === "1"
    ? "preview"
    : "public";

  return <Agenda showRoom={showRoomDetails(audience)} />;
}

export default function AgendaPage() {
  return (
    <main>
      <h1>Conference agenda</h1>
      <Suspense fallback={<p>Loading the agenda…</p>}>
        <AgendaForVisitor />
      </Suspense>
    </main>
  );
}

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 Guide

The 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.

"use client";

import { useState } from "react";

export function Agenda({ showRoom }: { showRoom: boolean }) {
  const [open, setOpen] = useState(false);

  return (
    <section data-agenda={showRoom ? "preview" : "standard"}>
      <h2>10:00 · Designing for print</h2>
      {showRoom && (
        <>
          <button aria-expanded={open} onClick={() => setOpen(!open)}>
            {open ? "Hide room" : "Show room"}
          </button>
          {open && <p>Room 204</p>}
        </>
      )}
    </section>
  );
}

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.

npm run build
npm run start -- -p 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.

import assert from "node:assert/strict";

async function agenda(cookie) {
  const response = await fetch("http://localhost:3100/agenda", {
    headers: cookie ? { Cookie: cookie } : {},
  });
  assert.equal(response.status, 200);
  return response.text();
}

const [standard, preview] = await Promise.all([
  agenda(""), agenda("agenda-preview=1"),
]);
assert.match(standard, /<section data-agenda="standard"/);
assert.doesNotMatch(standard, /<section data-agenda="preview"/);
assert.match(preview, /<section data-agenda="preview"/);
assert.doesNotMatch(preview, /<section data-agenda="standard"/);
console.log("Both agenda layouts arrived in the server HTML.");

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.

document.cookie = "agenda-preview=1; Path=/; SameSite=Lax";
location.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.

document.cookie = "agenda-preview=; Path=/; Max-Age=0";
location.reload();

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 GrowthBook

Ready to ship faster?

No credit card required. Start with feature flags, experimentation, and product analytics—free.

Simplified white illustration of a right angle ruler or carpenter's square tool.White checkmark symbol with a scattered pixelated effect around its edges on a transparent background.