Server-side Rendering Integration With Flagship [SSR]

📘 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 server-side rendering (SSR), content is rendered on the server for every page request.

During this process, we fetch all flags that target the visitor and pass them as props to the __app.js component. This data is then used to populate the FlagshipProvider component.

📘 Note

Once your app has been loaded in a browser, you can use the Flagship SDK in the same way as you would in a client-side rendering mode.


Implementation

📘 Setup a NextJS project

Please refer to this article link to set up a NextJS project.

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

yarn add @flagship.io/react-sdk

Initialize Flagship SDK server side

You have to create a module named startFlagshipSDK.js in the root directory of our project.

This module contains a function called startFlagshipSDK() which is responsible for initializing and starting the Flagship SDK.

The intention is to invoke this function when the server starts up.

We will invoke the startFlagshipSDK() function from within our next.config.js file.

This file is executed whenever we run the build, start, or dev commands for our Next.js application.

As such, we can use it as a convenient location to start the Flagship SDK.

Here is the refactor of next.config.js:

Initialize Flagship in the project

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

Our MyApp component will have two props: initialVisitorData and initialFlagsData.

The initialVisitorData prop contains data about the visitor, while the initialFlagsData prop contains the FlagsData that was fetched from the getServerSideProps function during a page request.

This data is used to populate the FlagshipProvider component.

There is no need to initialize the Flagship SDK again in the getServerSideProps function, as it has already been initialized when our Next.js application started up. Instead, we can simply create a visitor and fetch the relevant flags.

Here is the index page:

In the getServerSideProps of the index component page, we :

  • fetch the flags for the targeted visitor

  • pass the fetched flags to the page via props

Alternate Approach

We have refactored the index.jsx module. The startFlagshipSDKAsync function will no longer be called in the next.config.js file. Instead, it will be called on each page in the getServerSideProps function.

Do you have any feedback or suggestions? Would you like to see another tutorial? Contact us with your thoughts [email protected].

You can view the full code for this example on github

Last updated

Was this helpful?