diff --git a/packages/analytics-core/src/storage/cookie.ts b/packages/analytics-core/src/storage/cookie.ts index 41468226f..e4a7be6d2 100644 --- a/packages/analytics-core/src/storage/cookie.ts +++ b/packages/analytics-core/src/storage/cookie.ts @@ -51,7 +51,8 @@ export class CookieStorage implements Storage { async getRaw(key: string): Promise { const globalScope = getGlobalScope(); - const cookie = globalScope?.document?.cookie.split('; ') ?? []; + const cookieStr = globalScope?.document?.cookie ?? ''; + const cookie = cookieStr.split(/;\s*/); const match = cookie.find((c) => c.indexOf(key + '=') === 0); if (!match) { return undefined; diff --git a/packages/analytics-core/test/storage/cookies.test.ts b/packages/analytics-core/test/storage/cookies.test.ts index 5efc9ff2d..42b1d87ed 100644 --- a/packages/analytics-core/test/storage/cookies.test.ts +++ b/packages/analytics-core/test/storage/cookies.test.ts @@ -57,6 +57,16 @@ describe('cookies', () => { await cookies.remove('hello'); }); + test('should parse cookies without spaces', async () => { + const cookies = new CookieStorage(); + const value = { b: 2 }; + const encodedValue = btoa(encodeURIComponent(JSON.stringify(value))); + jest.spyOn(GlobalScopeModule, 'getGlobalScope').mockReturnValueOnce({ + document: { cookie: `hello=${encodedValue};hello2=${encodedValue}` }, + } as unknown as typeof globalThis); + expect(await cookies.get('hello2')).toEqual(value); + }); + test('should return undefined when global scope is not defined', async () => { const cookies = new CookieStorage(); await cookies.set('hello', [1]);