Flagship + Shopify Hydrogen Integration

📘 Github Repository

https://github.com/flagship-io/flagship-shopify-hydrogen-examplearrow-up-right

Overview

This guide demonstrates how to:

  • Integrate Flagship feature flags with Shopify Hydrogen (React-based framework)

  • Initialize the Flagship SDK with edge bucketing for optimal performance

  • Create visitor objects with contextual data in the app load context

  • Use feature flags in React components and loader functions

  • Handle server-side rendering with Flagship

  • Implement client-side hydration of feature flags

  • Conditionally display content based on feature flags

Prerequisites

Setup

  1. Clone the example repository:

  1. Install dependencies:

  1. Configure environment variables:

Create a .env file with your Flagship credentials:

  1. Start the development server:

Configure Vite for Flagship SDK

When using Flagship SDK with Hydrogen, proper Vite configuration is essential to prevent bundling issues. Update your vite.config.ts file with the following settings:

This configuration:

  • Excludes both the main and edge bundles from client-side optimization

  • Prevents Vite from processing the SDK in ways that might break its functionality

⚠️ Important: In Hydrogen (and other edge/SSR environments), always import from the edge bundle:

Initialize Flagship SDK in Hydrogen

The Flagship SDK is initialized at the application level to ensure it's available throughout your Hydrogen store. This is done in the flagship.ts helper file:

The SDK is configured with:

  • Edge Bucketing Mode: Makes flag decisions at the edge without API calls

  • Initial Bucketing Data: Pre-loaded campaign data for local decision-making

  • Revalidation Config: Refreshes cached flags every 15 seconds

  • Debug Logging: Helps troubleshoot during development

Create a Visitor in App Load Context

In Hydrogen, the Flagship visitor should be created in the createAppLoadContext function. This ensures the visitor is initialized once per request and available throughout the entire application context, including all loaders and actions.

Key Benefits of This Approach

  • Single Initialization: The visitor is created once per request, not in every loader

  • Global Availability: All loaders and actions can access context.fsVisitor

  • Session Integration: Visitor ID persists across requests using Hydrogen's session

  • Request Context: Can use request headers and other data for targeting

  • Performance: Flags are fetched once and reused throughout the request lifecycle

  • Type Safety: The visitor is available in the TypeScript context type

Accessing Visitor Data in Root Loader

The root loader serializes the visitor data for client-side hydration:

Provide Flagship Context to Your Application

To make Flagship available throughout your application, use the FsProvider component to wrap your application:

In the root Layout component, use this provider with the data from the loader:

Use Feature Flags in React Components

Once Flagship is initialized, you can use feature flags in your components with the useFsFlag hook:

Example 1: Change Text Based on a Flag

Example 2: Conditionally Display Content Based on a Flag

Use Feature Flags in Loader Functions

Since the Flagship visitor is now available in the app context, you can easily access feature flags in any loader function. This is powerful for server-side decision making before rendering.

Example 1: Control Product Count Based on a Flag

Example 2: Conditional Data Loading

Benefits of Using Flags in Loaders

  • Server-side Decision Making: Make feature decisions before page render, improving performance

  • Performance Optimization: Control data fetching based on flags to reduce unnecessary queries

  • A/B Testing: Test different data loading strategies and measure impact

  • Gradual Rollouts: Enable features progressively for different user segments

  • Consistent Context: Same visitor instance used across all loaders in a request

  • SEO Friendly: Flags resolved server-side are immediately available for crawlers

Best Practices for Loader Flags

  1. Access via Context: Always use context.fsVisitor rather than creating new visitors

  1. Default Values: Always provide default values for flags to ensure graceful fallbacks

Send analytics data back to Flagship

To measure the impact of your feature flags, you need to send analytics data back to Flagship. Analytics can be sent from two places:

  1. From loaders (Server-side) - Hits are pooled and sent in batch when Flagship.close() is called via waitUntil

  2. From components (Client-side) - Hits are pooled and sent in batch automatically in the background by the React SDK

Send Analytics from Loaders (Server-Side)

In loaders, calling sendHits doesn't immediately send the hits to Flagship. Instead, hits are added to a pool and sent in batch when Flagship.close() is called in the background via waitUntil.

How it works (Server-Side):

  1. Call fsVisitor.sendHits([...]) in any loader - hits are added to an internal pool

  2. Return the response immediately (non-blocking)

  3. Flagship.close() is called via waitUntil in the background

  4. All pooled hits are sent to Flagship in batch before the worker terminates

Example: Send analytics from route loaders

Send Analytics from Components (Client-Side)

In React components, when you call sendHits from an event handler (click, submit, etc.), the Flagship React SDK automatically collects hits into a pool and sends them in batch in the background on the client side. This provides optimal performance without blocking user interactions.

How it works (Client-Side):

  1. User triggers an event (click, submit, etc.)

  2. Call useflagship().sendHits([...]) - hits are added to the client-side pool

  3. Event handler completes immediately (non-blocking)

  4. Flagship React SDK automatically batches and sends pooled hits in the background

  5. User experience is never blocked by analytics

Example: Track product clicks

How Analytics Pooling Works

Server-Side (Loaders):

Client-Side (Components):

Benefits:

  • Non-blocking: User experience never interrupted by analytics

  • Efficient: Multiple hits batched into fewer network requests

  • Reliable: Server-side uses waitUntil to ensure delivery

  • Automatic: Client-side pooling handled by React SDK

  • Simple: Same sendHits API for both server and client

  • Performant: Reduces network overhead and improves responsiveness

Configure Content Security Policy for Flagship

When using Flagship with Hydrogen, you need to configure the Content Security Policy (CSP) to allow connections to Flagship's domains. This is done in entry.server.tsx:

Managing Bucketing Data

For optimal performance, Flagship uses bucketing data to make decisions locally without API calls. You can manage this data in several ways:

Development Approach

During development, you can use a static bucketing file:

  1. Fetch the bucketing data from Flagship CDN:

  1. Import it in your flagship.ts helper:

Production Approach

For production environments, it's better to trigger a redeployment when campaigns are updated rather than committing changes to your repository:

  1. Create a GitHub Action workflow file (.github/workflows/update-and-deploy.yml):

  1. Configure secrets in GitHub:

    • Go to your repository Settings > Secrets and variables > Actions

    • Add FLAGSHIP_ENV_ID with your Flagship environment ID

    • Add SHOPIFY_HYDROGEN_DEPLOYMENT_TOKEN with your deployment token

  2. Set up a webhook in the Flagship Platform:

    • Go to your Flagship project settings

    • Add a webhook URL pointing to GitHub Actions

    • Configure it to trigger on campaign updates

This approach:

  • Avoids cluttering your commit history with data changes

  • Provides immediate updates to production when campaigns change

  • Follows infrastructure-as-code best practices

  • Works well with modern deployment platforms like Shopify Oxygen

  • Maintains version control over your application code while keeping data fresh

⚠️ Note: If you're using a different hosting platform (Vercel, Netlify, AWS, etc.), replace the deployment step with the appropriate commands for your platform.

Troubleshooting

Common Issues and Solutions

1. CSP Violations

Problem: Browser console shows CSP violations for Flagship domains.

Solution: Ensure all Flagship domains are in your CSP configuration:

Learn More

Last updated

Was this helpful?