Skip to content

Instantly share code, notes, and snippets.

@jadenlemmon
Created November 1, 2021 17:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jadenlemmon/0be38797beed02dee36ef7618f81f76b to your computer and use it in GitHub Desktop.
Save jadenlemmon/0be38797beed02dee36ef7618f81f76b to your computer and use it in GitHub Desktop.
Example A/B Test Gatsby v4 SSR Cookies
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