Browser SDK cannot handle url-encoded cookie values
jeremyallison opened this issue · 1 comments
Expected Behavior
- Backend sets a cookie value (new format,
AMP_xxxxxx
). Cookie is returned to browser via aSet-Cookie
response header. - Frontend browser SDK parses existing cookie, uses
deviceId
already set by the backend, and uses it ✅
Current Behavior
- Backend sets cookie value (new format,
AMP_xxxxxx
). Cookie is returned to browser via aSet-Cookie
response header. - Frontend browser SDK fails to parse existing cookie, as its value is URL encoded. ❌
Possible Solution
Call decodeURIcomponent
on cookie value before atob
when parsing Amplitude cookie
Steps to Reproduce
Broken flow:
-
Manually set an Amplitude cookie in your browser, with an URL encoded value (as my Rails backend would) , for example
AMP_1310df2f88=JTdCJTIyZGV2aWNlSWQlMjIlM0ElMjJkZDU1YjIxNC0yNmY1LTQ5OTAtYjFiZi0zNTkzYTIxOTJlNDIlMjIlN0Q%3D
(JSON value would equal{"deviceId":"dd55b214-26f5-4990-b1bf-3593a2192e42"}
) -
Initialize browser SDK and let it parse this cookie
-
Inspect cookie set by browser SDK, decode its value :
{"deviceId":"72ac8556-1535-4fb2-bce4-f844bdb1d6cc","sessionId":xxxxx,"optOut":false,"lastEventTime":1234,"lastEventId":5}
deviceId
does not match. The JS SDK has ignored the backend cookie and set its owndeviceId
Fixed flow, proves what is broken:
-
Manually set an Amplitude cookie in your browser, with a value that has not been URL encoded, for example
AMP_1310df2f88=JTdCJTIyZGV2aWNlSWQlMjIlM0ElMjJkZDU1YjIxNC0yNmY1LTQ5OTAtYjFiZi0zNTkzYTIxOTJlNDIlMjIlN0Q=
<--⚠️ notice the=
is not encoded into%3D
here
(JSON value would equal{"deviceId":"dd55b214-26f5-4990-b1bf-3593a2192e42"}
) -
Initialize browser SDK and let it parse this cookie
-
Inspect cookie set by browser SDK, decode its value :
{"deviceId":"dd55b214-26f5-4990-b1bf-3593a2192e42","sessionId":xxxxx,"optOut":false,"lastEventTime":1234,"lastEventId":5}
deviceId
is now the proper value we set initially, found at step 1. The JS SDK has taken the initial cookie into account and re-used the existingdeviceId
Environment
- JS SDK Version: 2.4.1
- Installation Method: yarn
- Browser and Version: Chrome 121.0.6167.139
Please see #686 (comment) for more details.