|
1 |
| -import '../lib/polyfills'; |
| 1 | +import '../lib/polyfills'; // Necessary polyfills for the edge function scope |
2 | 2 | import {
|
3 | 3 | createInstance,
|
4 | 4 | eventDispatcher,
|
5 | 5 | } from '@optimizely/optimizely-sdk/dist/optimizely.lite.min.js';
|
6 | 6 | import optimizelyDatafile from '../lib/optimizely/datafile.json';
|
7 |
| -import { v4 } from 'uuid'; |
| 7 | +import { v4 as uuidv4 } from 'uuid'; |
8 | 8 |
|
| 9 | +// Constants for Optimizely client configuration |
9 | 10 | const CLIENT_ENGINE = 'EDGIO_EF';
|
10 | 11 | const COOKIE_NAME = 'optimizely_visitor_id';
|
11 | 12 |
|
| 13 | +/** |
| 14 | + * Handles incoming HTTP requests and applies A/B testing using Optimizely. |
| 15 | + * |
| 16 | + * @param {Request} request - The incoming HTTP request. |
| 17 | + * @param {Object} context - The context for this handler |
| 18 | + * @returns {Response} The HTTP response after applying A/B testing logic. |
| 19 | + */ |
12 | 20 | export async function handleHttpRequest(request, context) {
|
| 21 | + console.log(JSON.stringify(request.headers, null, 2)); // Log request headers for debugging |
| 22 | + |
| 23 | + // Retrieve or generate a unique user ID from cookies |
13 | 24 | const userId =
|
14 | 25 | request.headers
|
15 | 26 | .get('Cookie')
|
16 | 27 | ?.split(';')
|
17 | 28 | .find((cookie) => cookie.trim().startsWith(`${COOKIE_NAME}=`))
|
18 |
| - ?.split('=')[1] || v4(); |
| 29 | + ?.split('=')[1] || uuidv4(); |
19 | 30 |
|
20 |
| - // Create Optimizely instance using datafile downloaded at build time. |
| 31 | + // Create an Optimizely instance with the preloaded datafile and configuration |
21 | 32 | const instance = createInstance({
|
22 | 33 | datafile: optimizelyDatafile,
|
23 | 34 | clientEngine: CLIENT_ENGINE,
|
24 | 35 | eventDispatcher,
|
25 | 36 | });
|
26 | 37 |
|
27 |
| - // Return the original HTML if the instance is not created. |
| 38 | + // Early exit if the Optimizely instance isn't properly created |
28 | 39 | if (!instance) {
|
29 |
| - return Response.error('Optimizely instance unavailable.'); |
| 40 | + return new Response('Optimizely instance unavailable.', { status: 500 }); |
30 | 41 | }
|
31 | 42 |
|
32 |
| - await instance.onReady(); |
| 43 | + await instance.onReady(); // Ensures the Optimizely instance is ready before proceeding |
33 | 44 |
|
| 45 | + // Create a user context for the retrieved or generated user ID |
34 | 46 | const userContext = instance.createUserContext(userId.toString());
|
| 47 | + |
| 48 | + // Make a decision using Optimizely for the 'text_direction' feature |
35 | 49 | const decision = userContext.decide('text_direction');
|
36 |
| - const textDir = decision['enabled'] ? 'rtl' : 'ltr'; |
| 50 | + const textDir = decision.enabled ? 'rtl' : 'ltr'; // Determine text direction based on decision |
37 | 51 |
|
38 |
| - console.log( |
39 |
| - `[OPTIMIZELY] User ID: ${userId}, Text Direction: ${textDir}, Decision: ${JSON.stringify( |
40 |
| - decision |
41 |
| - )}` |
42 |
| - ); |
| 52 | + console.log(`[OPTIMIZELY] User ID: ${userId}, Text Direction: ${textDir}`); |
43 | 53 |
|
| 54 | + // Modify the request URL to append the determined text direction as a query parameter |
44 | 55 | const url = new URL('/', request.url);
|
45 | 56 | url.searchParams.set('dir', textDir);
|
46 |
| - const resp = await fetch(url, { |
47 |
| - edgio: { |
48 |
| - origin: 'edgio_self', |
49 |
| - }, |
| 57 | + |
| 58 | + // Fetch the `/` URL with the appended query parameter which will render a Next.js server page |
| 59 | + // with the text direction applied. `edgio_self` origin is used to fetch the URL from the same |
| 60 | + // environment which handles the Next.js routes. |
| 61 | + const response = await fetch(url.toString(), { |
| 62 | + edgio: { origin: 'edgio_self' }, |
50 | 63 | });
|
51 | 64 |
|
52 |
| - return resp; |
| 65 | + // Add the user ID to the response headers as a cookie to ensure the user experience consistency |
| 66 | + const cookie = `${COOKIE_NAME}=${userId}; Path=/; Max-Age=31536000; SameSite=Lax`; |
| 67 | + response.headers.append('Set-Cookie', cookie); |
| 68 | + |
| 69 | + return response; |
53 | 70 | }
|
0 commit comments