Server-side Rendering Integration With Flagship [SSR]

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

📘

Next.js is used for this example

For this example, we have used the Next.js framework.
If you need more examples, please contact us at [email protected]

How it works

In SSR, content is rendered server side on every page request during which we will fetch all flags targeting the visitor and passe them (flags) through a props to the __app.js component to feed the FlagshipProvider component.

Notes:

  • Once your app is loaded on a browser, you can use Flagship SDK like in client side rendering mode

Implementation

Please refer to this article link to set up 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/__page.jsx

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


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

}

export default MyApp

We have 2 props in MyApp component, initialVisitorData and initialFlagsData. The first one contains visitor data and the second contains the FlagsData fetched from getServerSideProps at request of page 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 ServerSide Rendering Integration With Flagship [SSR]</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 on the server side
export async function getServerSideProps(context) {
  const { res, req } = context;

  //Start the Flagship SDK
  const flagship = Flagship.start(
    process.env.NEXT_PUBLIC_ENV_ID,
    process.env.NEXT_PUBLIC_API_KEY,
    {
      fetchNow: false,
    }
  );

  //Get visitorId from cookies if exists
  const fs_visitorID_cookie = req.cookies["fs_visitorID_cookie"];

  const initialVisitorData = {
    id: fs_visitorID_cookie, // if not exists the SDK will generate one
    context: {
      any: "value",
    },
  };

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

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

  //set cookie fs_visitorID_cookie
  res.setHeader("Set-Cookie", `fs_visitorID_cookie=${visitor.visitorId}`);

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

On the getServerSideProps of the index component page, we :

  • fetch the flags for the targeted visitor
  • pass the fetched flags to the page via props

Any feedback?
Want another tutorial?
Contact us

See full code here : github