Skip to content

Commit e095266

Browse files
committed
Set cookie in response
1 parent b5378ac commit e095266

File tree

2 files changed

+37
-18
lines changed

2 files changed

+37
-18
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,53 +1,70 @@
1-
import '../lib/polyfills';
1+
import '../lib/polyfills'; // Necessary polyfills for the edge function scope
22
import {
33
createInstance,
44
eventDispatcher,
55
} from '@optimizely/optimizely-sdk/dist/optimizely.lite.min.js';
66
import optimizelyDatafile from '../lib/optimizely/datafile.json';
7-
import { v4 } from 'uuid';
7+
import { v4 as uuidv4 } from 'uuid';
88

9+
// Constants for Optimizely client configuration
910
const CLIENT_ENGINE = 'EDGIO_EF';
1011
const COOKIE_NAME = 'optimizely_visitor_id';
1112

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+
*/
1220
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
1324
const userId =
1425
request.headers
1526
.get('Cookie')
1627
?.split(';')
1728
.find((cookie) => cookie.trim().startsWith(`${COOKIE_NAME}=`))
18-
?.split('=')[1] || v4();
29+
?.split('=')[1] || uuidv4();
1930

20-
// Create Optimizely instance using datafile downloaded at build time.
31+
// Create an Optimizely instance with the preloaded datafile and configuration
2132
const instance = createInstance({
2233
datafile: optimizelyDatafile,
2334
clientEngine: CLIENT_ENGINE,
2435
eventDispatcher,
2536
});
2637

27-
// Return the original HTML if the instance is not created.
38+
// Early exit if the Optimizely instance isn't properly created
2839
if (!instance) {
29-
return Response.error('Optimizely instance unavailable.');
40+
return new Response('Optimizely instance unavailable.', { status: 500 });
3041
}
3142

32-
await instance.onReady();
43+
await instance.onReady(); // Ensures the Optimizely instance is ready before proceeding
3344

45+
// Create a user context for the retrieved or generated user ID
3446
const userContext = instance.createUserContext(userId.toString());
47+
48+
// Make a decision using Optimizely for the 'text_direction' feature
3549
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
3751

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}`);
4353

54+
// Modify the request URL to append the determined text direction as a query parameter
4455
const url = new URL('/', request.url);
4556
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' },
5063
});
5164

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;
5370
}

examples/v7-optimizely-edge/routes.ts

+2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import { nextRoutes } from '@edgio/next';
66
export default new Router()
77
// NextRoutes automatically adds routes for all Next.js pages and their assets
88
.use(nextRoutes)
9+
10+
// Add a custom route for the Optimizely Edge Function
911
.match('/optimizely', {
1012
edge_function: './edge-functions/main.js',
1113
});

0 commit comments

Comments
 (0)