šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Using the crossorigin and integrity attributes for script tags

By setting the crossorigin attribute we can decide if we send identifying informations, eg: auth cookies or credentials, when the browser makes a call for some external resources.

As an example when we deploy a React app on GitHub pages without any build step, we will need to load the React library from a CDN:

<script 
    crossorigin
    src="https://unpkg.com/react@18/umd/react.development.js">

This means that we are asking for the external react.development.js file, and we don't send any local identifying information to the https://unpkg.com website.

Writing <script crossorigin> is the same as saying <script crossorigin="anonymous">. To protect the user data, anonymity is the default behavior for cross origin requests.

On the other side, if we use use-credentials the browser will send the local user credentials when asking for an external resource:

<script 
    crossorigin="use-credentials"
    src="https://unpkg.com/react@18/umd/react.development.js">

This should be used with care as the external server will now get access to the local user data from your site.

For the moment, use-credentials and anonymous are the only values that can be used for crossorigin.

We can apply the crossorigin attribute to any the following HTML elements:

  • link resource elements
  • script files
  • media elements such as img, audio, video

Using crossorigin with the integrity attribute

Given that the external server we make the call to, can be hacked and send back malicious code, instead of something like the React library, we can add also the integrity attribute alongside crossorigin.

The server may provide us with a hash value that can be used with the integrity attribute:

<script 
    crossorigin
    integrity="sha256-MfvZlkHCEqatNoGiOXveE8FIwMzZg4W85qfrfIFBfYc= sha512"
    src="https://unpkg.com/react@18/umd/react.development.js">
/>

Using it we can make sure that the external resource is never loaded if the source has been manipulated.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *