diff --git a/vtex/loaders/orders/orderplaced.ts b/vtex/loaders/orders/orderplaced.ts index 90308f7ab..8722645e2 100644 --- a/vtex/loaders/orders/orderplaced.ts +++ b/vtex/loaders/orders/orderplaced.ts @@ -11,6 +11,37 @@ interface Props { orderId: string; } +/** + * Checkout cookies (CheckoutDataAccess + Vtex_CHKO_Auth) are set by VTEX right + * after an order is placed and are sufficient — and preferred — to access the + * order-placed page. The VtexIdclientAutCookie_* auth cookie can still be + * present in the browser even after it has expired, so sending it alongside the + * checkout cookies (or on its own when stale) causes the request to fail. + * Strategy: use checkout cookies when available; fall back to the auth cookie + * only when they are absent. + */ +function resolveOrderCookie(headers: Headers): string { + const all = getCookies(headers); + + const checkoutCookies = Object.fromEntries( + Object.entries(all).filter(([key]) => + key === CHECKOUT_DATA_ACCESS_COOKIE || key === VTEX_CHKO_AUTH + ), + ); + + if (Object.keys(checkoutCookies).length > 0) { + return stringify(checkoutCookies); + } + + const authCookies = Object.fromEntries( + Object.entries(all).filter(([key]) => + key.startsWith(VTEX_ID_CLIENT_COOKIE) + ), + ); + + return stringify(authCookies); +} + /** * @title Get Order Placed Order Details * @description Should be used on order placed page, the user must be authenticated or have access to the order through permissions or cookies @@ -21,16 +52,7 @@ export default async function loader( ctx: AppContext, ) { const { vcsDeprecated } = ctx; - const cookies = Object.fromEntries( - Object.entries(getCookies(req.headers)).filter(([key]) => - key.startsWith(VTEX_ID_CLIENT_COOKIE) || - // these two cookies are set by VTEX after order is placed on checkout and are - // used to access the order placed page - key === CHECKOUT_DATA_ACCESS_COOKIE || - key === VTEX_CHKO_AUTH - ), - ); - const cookie = stringify(cookies); + const cookie = resolveOrderCookie(req.headers); const isOrderGroup = !orderId.includes("-");