Server-side Rendering Integration With Flagship [SSR]
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.
Implementation
Once your project has been set up, you will need to install and initialize the Flagship React SDK.
yarn add @flagship.io/react-sdkInitialize 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.
🚧
The first request may take a little longer to process, but subsequent requests will be processed almost instantly.
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?

