섹션 1: Nextjs, Vercel edge 함수를 사용하여 A/B 테스트를 만들고 진폭 측정 분석을 사용합니다.

너의 사이트 데이터는 갈수록 커지지만 전환율은 결코 높지 않다.A/B 테스트를 실행하여 페이지 조회수 -> 등록 지표를 향상시킬 수 있는지 확인하기로 결정했습니다.본 강좌에서Nextjs,Verceledge 함수를 사용하여 간단한 a/B 테스트를 설정하고 진폭 측정 분석을 사용하는 방법을 소개할 것입니다.
Part 1: Github Repo
Part 1: Site Example

Note: We will not get into good experimentation practices in this article. This tutorial is only to show how to effectively set up an A/B test using edge functions and measure with amplitude


첫 번째 단계: 새 Nextjs 응용 프로그램 만들기

npx create-next-app -e with-tailwindcss feedback-widget코드 편집기에서 새로운 프로그램을 열면 테스트를 시작합니다.

2단계: 당신의 실험을 설정합니다


다음에 우리는 실험을 진행해야 한다.우리는 버튼 색상(보라색과 파란색)을 테스트해서 전환율을 높일 수 있는지 확인하기로 했다.이것은 우리의 첫 번째 실험이다. 우리는 그것exp001과 우리의 실험팀exp001-control(보라색 버튼)과 exp001-variant(파란색 버튼)을 잘 명명했다.

Note: We choose button color to keep it simple for this test. Changing a color is generally not an acceptable A/B test to run.


프로젝트에 experiment 폴더를 만듭니다.실험 폴더에는 두 개의 파일ab-testing.jsexp001.js이 필요합니다.

동료를 경계하다.


우리는 이미 실험한 두 패거리와 그들의 이름을 결정했다.전체 프로젝트에서 사용할 수 있도록 상수로 설정해야 합니다.exp001.js 파일에서 대기열과 쿠키를 명명합니다.
// experiment cohort names
export const COHORTS = ['exp001-control', 'exp001-variant'];
// experiment cookie name
export const COOKIE_NAME = 'exp001-cohort';

분류 교통


현재 우리는 우리의 동료가 생겼다. 우리의 ab-testing 파일에서 우리는 데이터 분할을 설정할 것이다.파일 상단에서 함수를 생성하여 임의의 수를 생성합니다.
function cryptoRandom() {
  return (
    crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1)
  );
}
우리의 예에서 우리는 crypto.getRandomValues()을 사용한다. 당신은 계속 사용할 수 있다Math.random(). (본 강좌에서 우리는 양자 간의 차이를 토론하지 않는다. 좋은 실천에 따라 당신이 가장 잘 아는 것을 사용한다!)이 함수는 우리에게 0과 1 사이의 무작위 수를 줄 것이다.그런 다음 함수를 만들어 위의 임의 수에 따라 대기열을 명명합니다.
export function getCohort(cohorts) {
  // Get a random number between 0 and 1
  let n = cryptoRandom() * 100;
  // Get the percentage of each cohort
  const percentage = 100 / cohorts.length;
  // Loop through the cohors and see if the random number falls
  // within the range of the cohort
  return (
    cohorts.find(() => {
      n -= percentage;
      return n <= 0;
      // if error fallback to control
    }) ?? cohorts[0]
  );
}
위의 getCohorts() 함수는 대기열의 수량에 따라 대기열을 짝수 부분으로 나눈다.
이제 우리는 우리의 그룹과 데이터 분할 기능이 생겼다.우리는 시험을 위해 우리의 홈페이지를 설정할 것이다.

3단계:중간부품


가장자리의 중간부품은 무엇입니까?


Vercel edge 함수는 방문객의 원본에 가까운 중간부품을 가장자리에 배치할 수 있도록 합니다.중간부품은 요청을 처리하기 전에 실행되는 실제 코드입니다.당신은 중간부품을 사용하여 많은 다른 기능을 수행할 수 있습니다. 예를 들어 우리가 지금처럼 A/B 테스트를 실행하고 로봇과 방향을 바꾸는 것을 막는 등입니다.중간부품 기능은 페이지에 대한 요청이 완료되기 전에 실행됩니다.

우리의 데이터 분할 중간부품을 설정합니다


중간부품을 실행하려면 _middleware.js 디렉터리에 pages 파일을 만들어야 합니다.이 중간부품은 모든 페이지가 요청이 완료되기 전에 실행됩니다.
import { getCohort } from '../experiment/ab-testing';
import { COHORTS, COOKIE_NAME } from '../experiment/exp001';

export function middleware(req) {
  // Get the cohort cookie
  const exp001 = req.cookies[COOKIE_NAME] || getCohort(COHORTS);
  const res = NextResponse.rewrite(`/${exp001}`);

  // For a real a/b test you'll want to set a cookie expiration
  // so visitors see the same experiment treatment each time
  // they visit your site

  // Add the cohort name to the cookie if its not there
  if (!req.cookies[COOKIE_NAME]) {
    res.cookie(COOKIE_NAME, exp001);
  }

  return res;
}
중간부품은 우선 대기열 쿠키를 가져오려고 시도하고, 없으면 단계 2에서 만든 getCohort() 함수를 실행합니다.그리고 응답을 다시 써서 대기열에 있는 방문자에게 정확한 페이지를 표시합니다.마지막으로 쿠키가 없으면 getCohort() 함수에서 쿠키를 가져와야 합니다. 브라우저의 후속 요청이 같은 페이지를 보일 수 있도록 응답이 있는 실험 쿠키를 보낼 것입니다.
현재 우리의 중간부품이 이미 설치되어 있으며, 우리는 홈페이지를 설정하여 우리의 실험을 나타낼 것이다.

4단계: 홈


현재 우리는 테스트 실행 홈 페이지를 설정해야 한다.이 페이지는 동적이기 때문에 페이지 디렉터리에 있는 index.js 파일을 [exp001].js 로 이름을 바꿔야 합니다.이것은 넥스트jsdynamic routing의 장점을 충분히 이용했다.정확한 페이지를 보여주려면 getStaticPaths 보여줄 경로 목록을 정의해야 합니다.우선, 단계 2에서 만든 대기열을 가져와야 합니다.
import { COHORTS } from '../experiment/exp001';
다음에, 우리는 getStaticPaths() 함수를 추가해서 모든 대기열을 순환시키고, 구축할 때 HTML로 보일 수 있는 경로를 정의해야 한다.우리는 대기열을 포함하는 exp001 대상을 경로의 매개 변수로 전달할 것이다.
export async function getStaticPaths() {
  return {
    paths: COHORTS.map((exp001) => ({ params: { exp001 } })),
    fallback: false,
  };
}
이제 우리는 우리의 길을 확정했으니, 그것들의 실제 행동을 좀 봅시다.임의로 할당된 큐를 보려면 useRouter를 가져옵니다.
import { useRouter } from 'next/router';
그런 다음 라우터를 선언하고 라우터 경로에서 대기열 상수를 생성합니다.
const router = useRouter();
const cohort = router.query.exp001;
본문에서 우리는 <pre> 표시로 현재 대기열을 나타낼 것이다
...
<div className="p-4">
  <pre>{cohort}</pre>
</div>
...
현재 페이지[exp001].js는 다음과 같습니다.
import { useRouter } from 'next/router';
import Head from 'next/head';
import { COHORTS } from '../experiment/exp001';

export default function Cohort() {
  const router = useRouter();
  const cohort = router.query.exp001;

  return (
    <div className="flex flex-col items-center justify-center min-h-screen py-2">
      <Head>
        <title>Simple Vercel Edge Functions A/B Test</title>
        <link rel="icon" href="/favicon.ico" />
        <meta
          name="description"
          content="An example a/b test app built with NextJs using Vercel edge functions"
        />
      </Head>

      <main className="flex flex-col items-center justify-center w-full flex-1 px-20 text-center">
        <h1 className="text-6xl font-bold">
          Vercel Edge Functions{' '}
          <span className="bg-gradient-to-r from-purple-700 to-blue-600 text-transparent bg-clip-text font-bold">
            A/B Test Example
          </span>{' '}
          With Amplitude
        </h1>
        <div className="p-4">
          <pre>{cohort}</pre>
        </div>
      </main>
    </div>
  );
}

export async function getStaticPaths() {
  return {
    paths: COHORTS.map((exp001) => ({ params: { exp001 } })),
    fallback: false,
  };
}
npm run dev로 로컬 서버를 시작하면 개발 도구에서 현재 대기열 + 실험 쿠키를 볼 수 있습니다.

새로 고칠 때, 같은 대기열을 볼 수 있습니다. 이것은 다음 요청이 브라우저에 설정된 실험 쿠키를 받고 있기 때문입니다.이렇게 하면 모든 페이지가 새로 고쳐지거나 후속 방문에서 방문객이 같은 그룹으로 귀속됩니다.대기열을 재설정하기 위해 실험 단추를 제거하는 함수와 단추를 만들었습니다. 대기열 재설정 단추를 누르면 중간부품이 새 요청getCohort() 함수를 실행합니다.
npm i js-cookie
import Cookies from 'js-cookie'
...
  const removeCohort = () => {
    // removes experiment cookie
    Cookies.remove('exp001-cohort');
    // reloads the page to run middlware
    // and request a new cohort
    router.reload();
  };
  ...
  <button type="button" onClick={removeCohort}>
    Reset Cohort
    </button>
...
현재, 대기열 리셋 단추를 누르면, 대기열 스위치를 볼 수 있습니다. getCohort() 함수에서 되돌아오는 무작위 수에 따라.
전체[exp001].js 코드:
import { useRouter } from 'next/router';
import Head from 'next/head';
import Cookies from 'js-cookie';
import { COHORTS } from '../experiment/exp001';

export default function Cohort() {
  const router = useRouter();
  const cohort = router.query.exp001;

  const removeCohort = () => {
    // removes experiment cookie
    Cookies.remove('exp001-cohort');
    // reloads the page to run middlware
    // and request a new cohort
    router.reload();
  };

  return (
    <div className="flex flex-col items-center justify-center min-h-screen py-2">
      <Head>
        <title>Simple Vercel Edge Functions A/B Test</title>
        <link rel="icon" href="/favicon.ico" />
        <meta
          name="description"
          content="An example a/b test app built with NextJs using Vercel edge functions"
        />
      </Head>

      <main className="flex flex-col items-center justify-center w-full flex-1 px-20 text-center">
        <h1 className="text-6xl font-bold">
          Vercel Edge Functions{' '}
          <span className="bg-gradient-to-r from-purple-700 to-blue-600 text-transparent bg-clip-text font-bold">
            A/B Test Example
          </span>{' '}
          With Amplitude
        </h1>
        <div className="p-4">
          <pre>{cohort}</pre>
        </div>

        <button type="button" onClick={removeCohort}>
          Reset Cohort
        </button>
      </main>
    </div>
  );
}

export async function getStaticPaths() {
  return {
    paths: COHORTS.map((exp001) => ({ params: { exp001 } })),
    fallback: false,
  };
}
현재 우리는 기능이 정상적인 사이트가 하나 생겨서 모든 사용자를 위해 그룹을 하나 분배한다.두 번째 부분에서 우리는 테스트 단추를 만들고 정확한 단추를 보여주며 진폭을 사용하여 우리의 실험 분석을 추적하는 방법을 소개할 것이다!
Part 1: Github Repo
Part 1: Site Example
A/B 테스트에 대한 피드백을 수집하시겠습니까?SerVoice로 5분 이내에 피드백 수집을 시작합니다!

좋은 웹페이지 즐겨찾기