| 8 | } |
| 9 | |
| 10 | export async function proxy(request: NextRequest) { |
| 11 | const cartId = await getCartId() |
| 12 | const code = await precompute(productFlags) |
| 13 | |
| 14 | // rewrites the request to the variant for this flag combination |
| 15 | const nextUrl = new URL( |
| 16 | `/${code}${request.nextUrl.pathname}${request.nextUrl.search}`, |
| 17 | request.url |
| 18 | ) |
| 19 | |
| 20 | // Add a header to the request to indicate that the stable id is generated, |
| 21 | // as it will not be present on the cookie request header on the first-ever request. |
| 22 | if (cartId.isFresh) { |
| 23 | request.headers.set('x-generated-cart-id', cartId.value) |
| 24 | } |
| 25 | |
| 26 | // response headers |
| 27 | const headers = new Headers() |
| 28 | headers.append('set-cookie', `cart-id=${cartId.value}`) |
| 29 | return NextResponse.rewrite(nextUrl, { request, headers }) |
| 30 | } |