diff --git a/src/api.js b/src/api.js index ad04cb7..d29d8b5 100644 --- a/src/api.js +++ b/src/api.js @@ -175,8 +175,13 @@ async function request( method: reqMethod, headers: reqHeaders, body: reqBody, - credentials: 'include', - mode: 'cors', + // Credentials and mode are only available in the browser + ...(!utils.isServer() + ? { + credentials: 'include', + mode: 'cors', + } + : undefined), }); const responseSession = response.headers.get('X-Session'); diff --git a/src/api.test.js b/src/api.test.js index 966007d..1458863 100644 --- a/src/api.test.js +++ b/src/api.test.js @@ -71,20 +71,48 @@ describe('api', () => { }); }); - it('should make a fetch request with credentials', async () => { + it('should make a fetch request without credentials', async () => { await api.request('get', '/test'); expect(fetch.mock.calls.length).toEqual(1); - expect(fetch.mock.calls[0][1]).toHaveProperty('credentials', 'include'); + expect(fetch.mock.calls[0][1]).not.toHaveProperty( + 'credentials', + 'include', + ); }); - it('should make a fetch request with cors', async () => { + it('should make a fetch request without cors', async () => { await api.request('get', '/test'); expect(fetch.mock.calls.length).toEqual(1); - expect(fetch.mock.calls[0][1]).toHaveProperty('mode', 'cors'); + expect(fetch.mock.calls[0][1]).not.toHaveProperty('mode', 'cors'); }); + describe('when making a request from the browser', () => { + beforeEach(() => { + // simulate browser + global.window = { document: {} }; + }); + + afterEach(() => { + delete global.window; + }); + + it('should make a fetch request with credentials', async () => { + await api.request('get', '/test'); + + expect(fetch.mock.calls.length).toEqual(1); + expect(fetch.mock.calls[0][1]).toHaveProperty('credentials', 'include'); + }); + + it('should make a fetch request with cors', async () => { + await api.request('get', '/test'); + + expect(fetch.mock.calls.length).toEqual(1); + expect(fetch.mock.calls[0][1]).toHaveProperty('mode', 'cors'); + }); + }); // describe: when making a request from the browser + it('should trim url', async () => { await api.request('get', '///test///'); diff --git a/src/cookie.js b/src/cookie.js index efe3ff1..e9d1997 100644 --- a/src/cookie.js +++ b/src/cookie.js @@ -7,7 +7,7 @@ function getCookie(name) { return undefined; } - const matches = document.cookie.match( + const matches = window.document.cookie?.match( new RegExp( '(?:^|; )' + name.replace(/([.$?*|{}()[]\\\/\+^])/g, '\\$1') + '=([^;]*)', ), diff --git a/src/utils/index.js b/src/utils/index.js index e91c029..5e2f29b 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -121,7 +121,7 @@ function reduce(arr, cb, init) { } function isServer() { - return !(typeof window !== 'undefined' && window && window.document); + return !(typeof window !== 'undefined' && window?.document); } function isFunction(func) {