Understanding and Fixing the “Strict-Origin-When-Cross-Origin” CORS Error

Tech Tips

Written by:

Reading Time: 4 minutes

The “Strict-Origin-When-Cross-Origin” CORS (Cross-Origin Resource Sharing) error is a frequent obstacle for developers when a web application seeks to obtain material from a different source. When it appears, requests may be refused and the application’s normal operation brought to a standstill. In this account, we shall look at why the error occurs, the manner in which it takes effect, and the practical measures by which it can be overcome.

What Does “Strict-Origin-When-Cross-Origin” Mean? 

This rule, known as “Strict-Origin-When-Cross-Origin,” is part of a browser’s defence against unsafe exchanges of information. It decides how the Referer header is sent when a request moves from one origin to another. It stands among the newer safeguards intended to preserve the privacy of the user whenever cross-origin communication takes place.

How It Works?

When a request is made within the same origin, the full address of the page from which it came is sent with it. For example, a request from https://example.com/page1 to https://example.com/page2 will carry the complete URL in its Referer.

When the request goes to a different origin, only the domain is sent, such as https://example.com. In this case, a call from https://example.com to https://anotherdomain.com will not reveal the full path.

If the request moves from a secure address (HTTPS) to one that is not secure (HTTP), the browser sends nothing in the Referer at all.

Why You’re Seeing This Error

This problem usually arises when:

1. A web application attempts to contact another origin, but the other server refuses to allow it. 

Also Read:  How to Fix Hulu P-DEV320 Error Explained: Causes, Quick Fixes, and Proven Troubleshooting Tips

2. It may be that the CORS settings on the server are too narrow or wrongly arranged. 

3. It may also happen because the browser, following its own security rules, withholds details from the Referer and so blocks the request.

Example of the Error

Your browser console will display  the error like this:

“Access to fetch at ‘https://api.example.com/data’ from origin ‘https://yourdomain.com’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The ‘Access-Control-Allow-Origin’ header has a value ‘null’ that is not equal to the supplied origin.”

How to Fix the “Strict-Origin-When-Cross-Origin” CORS Error

1. Set the Server to Permit Cross-Origin Requests

Alter the server’s reply so that it includes the proper Access-Control-Allow-Origin instruction. This tells the browser which domains may reach the resource.

To permit every origin:

Access-Control-Allow-Origin: *

To permit one origin only:

Access-Control-Allow-Origin: https://yourdomain.com

To decide at the time of request: have the server read the Origin header and return an Access-Control-Allow-Origin value to match.

2. Deal with Preflight Requests

Before some cross-origin calls, the browser sends an OPTIONS request to ask the server what is allowed. The server must be able to answer these requests in full.

Response Headers Example:

“Access-Control-Allow-Origin: https://yourdomain.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization”

3. Use HTTPS for Both Origins

Make certain that both the client and the server are reached through HTTPS. Many modern browsers place heavier restrictions on requests that mix secure and insecure addresses, such as from HTTPS to HTTP.

4. Alter Browser Behaviour (For Development Only)

When you build and test, you can turn off CORS checks or bend the browser to your will. Do it with care. It can make you weak to attack.

Also Read:  How To Cancel Planet Fitness Membership: Step-by-Step Instructions, Fees, and Alternatives Explained 

Use a proxy. Let it send your calls to the API so they seem to come from one place.

Example in Node.js: “const { createProxyMiddleware } = require(‘http-proxy-middleware’);  app.use(‘/api’, createProxyMiddleware({     target: ‘https://api.example.com’,     changeOrigin: true, }));”

Or use an extension. There is one called “CORS Unblock” for Chrome. Use it only when the field is safe.

5. Adjust the Frontend Requests

Check that your frontend code sends the right headers when making calls across origins.
Example using the Fetch API:

 “fetch(‘https://api.example.com/data’, {
  method: ‘GET’,
  headers: {
    ‘Content-Type’: ‘application/json’,
  },
  credentials: ‘include’, // For cookies or authentication tokens
})
.then(response => response.json())
.catch(error => console.error(‘CORS Error:’, error));”

6. Change the Browser’s CORS Policy

For work on a local machine, the browser can be started with looser security rules. In Chrome, for instance: 

“chrome.exe –disable-web-security –user-data-dir=”C:\chrome-dev””

Warning: This is only to be done in testing, never in a live system, as it removes important safeguards.

Conclusion

The fight against the CORS error of Strict-Origin-When-Cross-Origin can be like fighting with a bouncer who is too protective to allow your web requests into the club- even when you have legitimate business in the club. Although this is a security measure in place to keep the digital riffraff out, it can be a real pain in the neck when it rejects your perfectly innocent API calls. 

The positive news? By configuring your server, implementing HTTPS, and a pinch of patience, you will normally be able to persuade this digital bouncer to allow your requests to pass. Just keep those Access-Control headers set up right, manage those preflight requests like a champ, and do not be tempted to turn off CORS in production forever, that is the equivalent of getting rid of the bouncer and letting the crazies in. 

Also Read:  Nextgen Healthfusion Login: A Complete Step-By-Step Guide to Follow in 2023

Consider CORS errors to be your browser telling you, trust, but verify. When you have gained that trust with the right set up, your cross-origin requests will be as smooth as a well-organized VIP line.

FAQs

Q1: What exactly is this “Strict-Origin-When-Cross-Origin” thing anyway?

A: Imagine it as your browser paranoid security guard that determines to what extent you are going to share your information visiting various websites. It decides what is disclosed in the Referer header, a digital doorman who will display your full address, your neighborhood, or remain totally silent based on where you are going.

Q2: Can I just disable CORS and call it a day?

A: Turning off CORS is equivalent to taking all the locks off your house since you are always losing your keys. It is effective at local development, but in production, it is like sharing your credit card info on social media, technically it is possible but it is an epic fail.

Q3: Why does mixing HTTP and HTTPS cause such drama?

A: Mixing HTTP with HTTPS is to modern browsers as oil and water, they simply do not mix. It is a security mechanism that is intended to avoid downgrade attacks in which malicious parties attempt to steal your secure information. 

Q4: Is there a quick fix that doesn’t involve server configuration?

A: For development, you can use a proxy server to disguise your requests to look like they come as the same origin- it is like wearing a mask to deceive the security guard. There is no way around proper server configuration, however, in production. You have to work and put in those headers right.