Tutorial - Feature Flags in an SSR Next.js app
Strapline
Using Feature Flags in a server-side rendered Next.js app
Why should we do it?
We're missing a tutorial covering this use case. From a customer:
I'd like a complex tutorial covering.
- Fetching a featureFlag at the edge (checking for an existing ph cookie, setting one if missing)
- Entering a user into a featureFlag group (i.e control or test) at the edge and setting that in the cookie
- Using that data to SSR a page in Next.js (different component per control/test group
- Bootstrapping that SSR'd data into the React client-side posthog client, to avoid hydration errors.
Community thread: https://posthog.com/questions/more-details-about-ssr-and-hydration
Headlines options
Using Feature Flags in a server-side rendered Next.js app
Outline
See above
Hi there! This is my request! You will run into issues passing data from edge middleware to getServerSideProps.
Some clues that might be helpful:
I have a bonkers hack where I set feature flag decisions as headers at the edge, and use that (if there's no cookie already set.)
I also wrote my own PostHogProvider that renders the distinctId and featureFlags to window.FLAGS - something like that, on my phone so can't check. That seems to bootstrap the PH client correctly. I based it off a vanilla SSR bootstrap example.
Then I have my own useFeatureFlagVarianKey that can return a value in an SSR context, passing the values from middleware or gSSP through to the provider in _app.js via pageProps.
Good luck! It's great now it works for me. But I suspect would be helpful to come up with an "official solution".
P.S Clerk have a good blog on passing data from Middleware to gSSP
Thanks for the further details, we have this https://posthog.com/tutorials/nextjs-bootstrap-flags but I think there is more I can add around SSR. Thanks for mentioning the Clerk post, I'll check it out.
I think this is the Clerk post: https://clerk.com/blog/nextjs-pass-value-from-middleware-to-api-routes-and-getserversideprops
Hi, do we have a similar tutorial with Remix?
Hi, do we have a similar tutorial with Remix?
On my to-do list and moving up thanks to your feedback 😄 https://github.com/PostHog/posthog.com/issues/7026
Hi, do we have a similar tutorial with Remix?
On my to-do list and moving up thanks to your feedback 😄 #7026
When you're done with the Remix tutorial please drop a link below