-
-
Save davidpaulsson/989f22bd9dd2f41ce50aacba13436e95 to your computer and use it in GitHub Desktop.
Example A/B Test Gatsby v4 SSR Cookies
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { sample } from 'lodash'; | |
import React from 'react'; | |
import cookie from 'cookie'; | |
import Layout from '../components/layout'; | |
import HomeV1 from '../components/scenes/home/v1'; | |
import HomeV2 from '../components/scenes/home/v2'; | |
const EXPERIMENT_OPTIONS = { | |
v1: HomeV1, | |
v2: HomeV2, | |
}; | |
const IndexPage = ({ serverData }) => { | |
return ( | |
<Layout navProps={{ fluid: false }}> | |
{React.createElement( | |
EXPERIMENT_OPTIONS[serverData?.sampleVersion || 'v2'], | |
)} | |
</Layout> | |
); | |
}; | |
export function getServerData(req) { | |
const headers = {}; | |
const cookies = cookie.parse(req.headers.get('cookie')); | |
let sampleVersion = cookies.sample; | |
if (!sampleVersion) { | |
const activeSample = sample(['v1', 'v2']); | |
headers['Set-Cookie'] = cookie.serialize('sample', activeSample, { | |
httpOnly: true, | |
maxAge: 60 * 60 * 24 * 14, // 2 weeks | |
}); | |
sampleVersion = activeSample; | |
} | |
return { | |
props: { sampleVersion }, | |
headers, | |
}; | |
} | |
export default IndexPage; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment