JavaScript / frontend widgets are a very popular way to enhance web sites and they have a wide variety of uses. Some examples are:

Google Analytics - Collect data from your visitors in order to present detailed website traffic reports

Facebook Widgets - Engage your visitors in social media

AddThis - Easy way to letting your visitors share content on your site

Google Charts - A wide variety of interactive charts

JS CDN - Serve static JS libraries via CDNs

As you might know, these kind of widgets might slow down the loading of your site, which in turn may reduce your SEO-score. But perhaps more troubling is that they can steal your visitors' data, including hijacking their sessions by retrieving session cookies.

Solutions

So here are a few strategies that might help you to mitigate the problem.

1. Host JavaScript files yourself

The problem with this approach is that interactive widgets and visitor data collection for analytics is out of the question - you will not be able to run Google Analytics or use Facebook widgets.

2. Restrict your Content-Security-Policy

Modern web browser can help you control from where and how external scripts may be loaded and executed if you add a Content-Security-Policy to the header section of your markup, for example:

<head> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; "> <!-- Other headers --> <head/>

The problem with this solution is similar to the first one, as you can't restrict what kind of data that external scripts have access to, only from where and through what protocol they were loaded.

Read more about CSP here.

3. Set HttpOnly-attribute to sensitive cookies

A third approach might be to set the HttpOnly-attribute to sensitive cookies. This will protect your cookies from being accessed by any frontend code. The problem with this approach is:

It only protects cookies, not other sensitive data (as form content or local storage)

It might not always be a viable solution when applied to a SPA - Singe Page Application as the JS layer may have to have access to the session cookie.

Read more about HttpOnly at OWASP.