@@ -147,59 +147,44 @@ const app = new Hono();
147147
148148const NAME = " myExampleWorkersABTest" ;
149149
150+ // Enable passthrough to allow direct access to control and test routes
151+ app .all (" /control/*" , (c ) => fetch (c .req .raw ));
152+ app .all (" /test/*" , (c ) => fetch (c .req .raw ));
153+
150154// Middleware to handle A/B testing logic
151155app .use (" *" , async (c ) => {
152- // Enable Passthrough to allow direct access to control and test routes
153- if (c .req .path .startsWith (" /control" ) || c .req .path .startsWith (" /test" )) {
154- return fetch (c .req .raw );
155- }
156+ const url = new URL (c .req .url );
156157
157158 // Determine which group this requester is in
158159 const abTestCookie = getCookie (c , NAME );
159160
160161 if (abTestCookie === " control" ) {
161162 // User is in control group
162- c .req .path = " /control" + c .req .path ;
163- return fetch (url );
163+ url .pathname = " /control" + c .req .path ;
164164 } else if (abTestCookie === " test" ) {
165165 // User is in test group
166- url .pathname = " /test" + url .pathname ;
167- return fetch (c .req .url );
166+ url .pathname = " /test" + c .req .path ;
168167 } else {
169168 // If there is no cookie, this is a new client
170169 // Choose a group and set the cookie (50/50 split)
171170 const group = Math .random () < 0.5 ? " test" : " control" ;
172171
173172 // Update URL path based on assigned group
174173 if (group === " control" ) {
175- c . req . path = " /control" + c .req .path ;
174+ url . pathname = " /control" + c .req .path ;
176175 } else {
177- c . req . path = " /test" + c .req .path ;
176+ url . pathname = " /test" + c .req .path ;
178177 }
179178
180- // Fetch from origin with modified path
181- const res = await fetch (c .req .url );
182-
183- // Create a new response to avoid immutability issues
184- const newResponse = new Response (res .body , res );
185-
186179 // Set cookie to enable persistent A/B sessions
187180 setCookie (c , NAME , group , {
188181 path: " /" ,
189- // Add additional cookie options as needed:
190- // secure: true,
191- // httpOnly: true,
192- // sameSite: 'strict',
193182 });
183+ }
194184
195- // Copy the Set-Cookie header to the response
196- newResponse .headers .set (
197- " Set-Cookie" ,
198- c .res .headers .get (" Set-Cookie" ) || " " ,
199- );
185+ const res = await fetch (url );
200186
201- return newResponse ;
202- }
187+ return c .body (res .body , res );
203188});
204189
205190export default app ;
0 commit comments