Skip to content

embed clientInitializeResponse and statsigUser #1116

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 0 additions & 29 deletions flags-sdk/experimentation-statsig/app/api/bootstrap/route.ts

This file was deleted.

7 changes: 7 additions & 0 deletions flags-sdk/experimentation-statsig/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ export default function RootLayout({
{children}
<Toaster />
<VercelToolbar />
<script
id="embed"
// biome-ignore lint/security/noDangerouslySetInnerHtml: <explanation>
dangerouslySetInnerHTML={{ __html: '' }}
suppressHydrationWarning
type="application/json"
/>
</body>
</html>
)
Expand Down
52 changes: 42 additions & 10 deletions flags-sdk/experimentation-statsig/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { type NextRequest, NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { precompute } from 'flags/next'
import { productFlags } from '@/flags'
import { getStableId } from './lib/get-stable-id'
import { getCartId } from './lib/get-cart-id'
import { HTMLRewriter } from 'htmlrewriter'
import { statsigAdapter } from '@flags-sdk/statsig'
import { identify } from './lib/identify'
import { safeJsonStringify } from 'flags'

export const config = {
matcher: ['/', '/cart'],
Expand All @@ -19,19 +23,47 @@ export async function middleware(request: NextRequest) {
request.url
)

// Add a header to the request to indicate that the stable id is generated,
// as it will not be present on the cookie request header on the first-ever request.
// Create new headers with the original request headers
const headers = new Headers(request.headers)

// Add new headers if needed
if (cartId.isFresh) {
request.headers.set('x-generated-cart-id', cartId.value)
headers.set('x-generated-cart-id', cartId.value)
}

if (stableId.isFresh) {
request.headers.set('x-generated-stable-id', stableId.value)
headers.set('x-generated-stable-id', stableId.value)
}

// response headers
const headers = new Headers()
headers.append('set-cookie', `stable-id=${stableId.value}`)
headers.append('set-cookie', `cart-id=${cartId.value}`)
return NextResponse.rewrite(nextUrl, { request, headers })
// Create a new request with the modified headers
const modifiedRequest = new Request(nextUrl, { ...request, headers })

const [statsig, statsigUser] = await Promise.all([
statsigAdapter.initialize(),
identify(),
])
const clientInitializeResponse = statsig.getClientInitializeResponse(
statsigUser,
{ hash: 'djb2' }
)

const response = await fetch(modifiedRequest)
const rewriter = new HTMLRewriter()
rewriter.on('script#embed', {
element(element) {
element.setInnerContent(
safeJsonStringify({ clientInitializeResponse, statsigUser }),
{ html: true }
)
// element.setAttribute('style', 'display: block')
},
})
const modifiedResponse = rewriter.transform(response)
const h = new Headers(modifiedResponse.headers)
h.append('set-cookie', `stable-id=${stableId.value}`)
h.append('set-cookie', `cart-id=${cartId.value}`)
return new Response(modifiedResponse.body, {
...modifiedResponse,
headers: h,
})
}
3 changes: 2 additions & 1 deletion flags-sdk/experimentation-statsig/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@
"@vercel/edge": "1.2.1",
"@vercel/edge-config": "1.4.0",
"@vercel/toolbar": "0.1.33",
"framer-motion": "12.4.7",
"clsx": "2.1.1",
"flags": "^3.1.1",
"framer-motion": "12.4.7",
"htmlrewriter": "^0.0.12",
"nanoid": "5.1.2",
"next": "15.2.1-canary.4",
"react": "^19.0.0",
Expand Down
8 changes: 8 additions & 0 deletions flags-sdk/experimentation-statsig/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

60 changes: 36 additions & 24 deletions flags-sdk/experimentation-statsig/statsig/statsig-provider.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
'use client'

import { Statsig } from '@flags-sdk/statsig'
/**
* This file exports a StatsigProvider with a client-side bootstrap.
* It requires a client-side fetch to retrieve the bootstrap payload.
*
* The bootstrap reads the data embedded by Edge Middleware.
*
* Elements that determine page layout should have precomputed variants with flags-sdk.
* Exposures can be logged with helpers in the `statsig-exposure` module.
*/

import type { Statsig, StatsigUser } from '@flags-sdk/statsig'
import {
LogLevel,
StatsigProvider,
useClientBootstrapInit,
} from '@statsig/react-bindings'
import { StatsigAutoCapturePlugin } from '@statsig/web-analytics'
import { createContext, useMemo } from 'react'
import useSWR from 'swr'
import { createContext, useMemo, useState, useEffect } from 'react'

export const StatsigAppBootstrapContext = createContext<{
isLoading: boolean
Expand All @@ -25,6 +25,16 @@ export const StatsigAppBootstrapContext = createContext<{
error: null,
})

export function useEmbed<T>(id: string, initialData?: T) {
const [data, setData] = useState<T | undefined>(initialData || undefined)
useEffect(() => {
// biome-ignore lint/style/noNonNullAssertion: <explanation>
const text = document.getElementById(id)!.textContent
setData(text ? JSON.parse(text) : undefined)
}, [id])
return data
}

function BootstrappedStatsigProvider({
user,
values,
Expand All @@ -51,35 +61,37 @@ export function StaticStatsigProvider({
}: {
children: React.ReactNode
}) {
const { data, error } = useBootstrap()
const values = useMemo(() => JSON.stringify(data), [data])
// wait for the script#embed to appear and read its contents as json
// TODO use actual embed library
const data = useEmbed<{
statsigUser: StatsigUser
clientInitializeResponse: Awaited<
ReturnType<typeof Statsig.getClientInitializeResponse>
>
}>('embed')

const values = useMemo(
() => (data ? JSON.stringify(data.clientInitializeResponse) : null),
[data]
)

if (!data) {
if (!data || !values) {
return (
<StatsigAppBootstrapContext.Provider value={{ isLoading: true, error }}>
<StatsigAppBootstrapContext.Provider
value={{ isLoading: true, error: null }}
>
{children}
</StatsigAppBootstrapContext.Provider>
)
}

return (
<StatsigAppBootstrapContext.Provider value={{ isLoading: false, error }}>
<BootstrappedStatsigProvider user={data.user} values={values}>
<StatsigAppBootstrapContext.Provider
value={{ isLoading: false, error: null }}
>
<BootstrappedStatsigProvider user={data.statsigUser} values={values}>
{children}
</BootstrappedStatsigProvider>
</StatsigAppBootstrapContext.Provider>
)
}

const fetcher = (url: string) =>
fetch(url, {
headers: {
Vary: 'Cookie',
},
}).then((res) => res.json())

export function useBootstrap() {
return useSWR<
Awaited<ReturnType<typeof Statsig.getClientInitializeResponse>>
>('/api/bootstrap', fetcher)
}