Hi y'all. I'm using growthbook in next.js as middl...
# ask-questions
g
Hi y'all. I'm using growthbook in next.js as middleware. I am not running it on the frontend at all. I have GA4 as a datasource running in bigquery, at what point do I send the data about the experiment to GA4? Here is the code snippet
Copy code
import { NextResponse } from 'next/server'
import { GrowthBook } from '@growthbook/growthbook'

const COOKIE = 'visitor_id'

export function middleware(request, event) {
  let visitor_id = request.cookies.get(COOKIE)?.value || crypto.randomUUID()

  const growthbook = new GrowthBook({
    apiHost: '<https://cdn.growthbook.io>',
    clientKey: 'xxxx',
    attributes: { id: visitor_id },
    trackingCallback: (exp, res) => {
      console.log('key and variation ID:', exp.key, res.variationId)
    },
  })

  const handleGrowthBookInit = async () => {
    let res = NextResponse.next()

    try {
      await growthbook.init()

      if (growthbook.isOn('list-page')) {
        const result = growthbook.evalFeature("list-page");

        if (result.experimentResult && result.experimentResult.key === '1') {
          console.log('In Experiment!');
          const url = request.nextUrl.clone()
          url.pathname = '/c/dishwashers'
          res = NextResponse.rewrite(url)
        }
      }

      if (!request.cookies.has(COOKIE)) {
        res.cookies.set(COOKIE, visitor_id)
      }
    } catch (err) {
      console.error('GrowthBook failed to initialize', err)
    }

    return res
  }

  const promise = handleGrowthBookInit()

  event.waitUntil(promise)

  return promise
}

export const config = {
  matcher: '/dishwashers/',
}