1- export default {
2- async fetch ( request , env ) {
3- const url = new URL ( request . url ) ;
4- if ( url . pathname . startsWith ( '/api/' ) ) {
5- // TODO: Add your custom /api/* logic here.
6- return new Response ( 'Ok' ) ;
1+ const cookieName = "ab-homepage-test-cookie"
2+ const newHomepagePathName = "/index-test"
3+
4+ const abTest = async ( context ) => {
5+ const url = new URL ( context . request . url )
6+ // if homepage
7+ if ( url . pathname === "/" ) {
8+ // if cookie ab-homepagetest-cookie=new then change the request to go to /index-test
9+ // if no cookie set, pass x% of traffic and set a cookie value to "current" or "new"
10+
11+ let cookie = request . headers . get ( "cookie" )
12+ // is cookie set?
13+ if ( cookie && cookie . includes ( `${ cookieName } =new` ) ) {
14+ // pass the request to /test
15+ url . pathname = newHomepagePathName
16+ return context . env . ASSETS . fetch ( url )
17+ } else {
18+ const percentage = Math . floor ( Math . random ( ) * 100 )
19+ let version = "current" // default version
20+ // change pathname and version name for 50% of traffic
21+ if ( percentage < 50 ) {
22+ url . pathname = newHomepagePathName
23+ version = "new"
24+ }
25+ // get the static file from ASSETS, and attach a cookie
26+ const asset = await context . env . ASSETS . fetch ( url )
27+ let response = new Response ( asset . body , asset )
28+ response . headers . append ( "Set-Cookie" , `${ cookieName } =${ version } ; path=/` )
29+ return response
730 }
8- // Otherwise, serve the static assets.
9- // Without this, the Worker will error and no assets will be served.
10- return env . ASSETS . fetch ( request ) ;
11- } ,
12- }
31+ }
32+ return context . next ( )
33+ } ;
34+
35+ export const onRequest = [ abTest ] ;
0 commit comments