Search code examples
javascriptangularsecuritysession-cookiesweb-worker

How to pass main website's secured session cookie to web worker and use it there to call APIs


We use a secure session cookie and the back-end set the cookie through the login API. Http requests are cross-origin. I want to use web-workers to do some calculations and call certain APIs. cookies will be lost in web worker API calls despite using credentials: 'include'. What can I do if I don't want to pass back API calls to the main thread?


Solution

  • Actually, the web worker HAS main thread cookies including secured ones. to use credentials you should mention credentials: 'include' in fetch request params as follows:

       fetch('https://example.com/profile', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data),
    
          // this line is important:
          credentials: 'include', // include, same-origin or omit ... as your conditions
        
        })
        .then(response => response.json())
        .then(data => {
          console.log('Success:', data);
        })