Static-site generation integration with Flagship [SSG]

This guide explains you how to use Flagship with nextJS using SSG mode.

How it works

In Static-site generation, content is rendered at build time during which we will fetch all flags targeting a unique flagship visitor and pass them (flags) through a props to the __app.js component to feed the FlagshipProvider component.

🚧

Notes

  • All your visitors will see the same flags because at build time we can only target one visitor.
  • If you update your campaigns from Flagship dashboard, you will also need to rebuild your app to update your static content. Check
  • Once your app is loaded on a browser, you can use Flagship SDK the same way as in client side rendering mode

Implementation

Please refer to this article link to setup a NextJS project.

Once your project is set up, you need to install and initialize the Flagship React SDK.

yarn add @flagship.io/react-sdk

We will customize the next component App to initialize the Flagship SDK.

// pages/_app.jsx

import { FlagshipProvider } from '@flagship.io/react-sdk'
import '../styles/globals.css'


function MyApp({ Component, pageProps }) {
  const { initialVisitorData, flagsData } = pageProps
  return (
    <FlagshipProvider
      envId={process.env.NEXT_PUBLIC_ENV_ID}
      apiKey={process.env.NEXT_PUBLIC_API_KEY}
      visitorData={initialVisitorData || {}}
      initialFlagsData={flagsData}
    >
      <Component {...pageProps} />
    </FlagshipProvider>)

}

export default MyApp

We have 2 props in MyApp component, initialVisitorData and flagsData. the first one contains visitor data and the second contains the FlagsData fetched from getStaticProps at build time to feed FlagshipProvider.


Here is the index page:

//pages/index.jsx

import {
  useFsFlag,
  useFlagship,
  Flagship,
  HitType,
  EventCategory,
} from "@flagship.io/react-sdk";
import styles from "../styles/Home.module.css";

export default function Home() {
  const fs = useFlagship();

  //get flag
  const myFlag = useFsFlag("my_flag_key", "default-value");

  const onSendHitClick = () => {
    fs.hit.send({
      type: HitType.EVENT,
      category: EventCategory.ACTION_TRACKING,
      action: "click button",
    });
  };

  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <h1>Next Static site generation integration with Flagship [SSG]</h1>
        <p>flag key: my_flag_key</p>
        <p>flag value: {myFlag.getValue()}</p>
        <button
          style={{ width: 100, height: 50 }}
          onClick={() => {
            onSendHitClick();
          }}
        >
          Send hits
        </button>
      </main>
    </div>
  );
}

// This function runs only at build time
export async function getStaticProps() {
  //Start the Flagship SDK
  const flagship = Flagship.start(
    process.env.NEXT_PUBLIC_ENV_ID,
    process.env.NEXT_PUBLIC_API_KEY,
    {
      fetchNow: false,
    }
  );

  const initialVisitorData = {
    id: "my_visitor_id",
    context: {
      any: "value",
    },
  };

  // Create a new visitor
  const visitor = flagship.newVisitor({
    visitorId: initialVisitorData.id,
    context: initialVisitorData.context,
  });

  // //Fetch flags
  await visitor.fetchFlags();

  // Pass data to the page via props
  return {
    props: {
      flagsData: visitor.getFlagsDataArray(),
      initialVisitorData,
    },
  };
}

On the getStaticProps of the index component page, we :

  • Fetch the flags for the targeted visitor
  • Pass the fetched flags to the page via props

How to automate rebuilding

To automate the rebuild, we need to use flagship Webhooks Integrations.

When your campaigns are updated, a webhook called [environment] synchronized will be triggered

We will use this event to rebuild our app because our flags have been updated.


772

In this guide, we are going to deploy our app to Netlify.com but the process is similaire to other platforms even if you want to use a CI/CD.


We will proceed in 2 steps:

1. Once your app is deployed to netlify.com, we create a build hook from Netlify setting.

Go to site settings -> Build and deploy

1158 1162

2. In the Flagship plateform

Go to settings -> integrations and webhooks tab

Choose [environment] synchronized event and set your netlify hook url than create.

1586

Any feedback?
Want another tutorial?
Contact us

See full code here : github