Open In App

What is same-origin policy with regards to JavaScript ?

Last Updated : 13 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Same origin policy is a security mechanism that restricts a resource that is loaded in one particular origin from another origin.

This means that an origin cannot access the content from some other origin. This also prevents any kind of suspicious activities that are happening indirectly through a particular origin.

Two origins are considered as same if their URLs have the same hostname, port, and protocol.

Example:

http://example.com:80/data/
http://example.com:80/file/data

The above two links are of the same origin as the scheme, hostnames, and port are the same.

http://example.com:144/data/
https://example.com:80/file/data

The above two links are not the same as the port and scheme are different.

Due to this policy, one cannot make an indirect request to an origin. The asynchronous requesting mechanisms like AXIOS, AJAX, and Fetch requests show an error message on a request from some other origin and this is a result of CORS which stands for CROSS ORIGIN RESOURCE SECURITY  and which happens when origins do not match.

There are also some exceptions to this policy, which are:

  • JavaScript with <script src=”…”></script> is allowed with no error indications.
  • CSS applied with <link rel=”stylesheet” href=”…”> is allowed.
  • Images displayed by <img/>.
  • Media played by <video/> and <audio/>.
  • External resources embedded with <object> and <embed>.
  • Fonts applied with @font-face. Some browsers allow cross-origin fonts, while others require same-origin.
  • Anything embedded by <iframe> is allowed.

The above cases also make a cross-origin request but the browsers do not restrict it. Cross-origin writes are also allowed. For example, form submissions.

Let us discuss a situation where CORS occurs:

Example 1: In the below example we will create two files. Follow The below steps to illustrate the example properly:

  • HTML: This file makes an AJAX request
  • JS file: This file return the response

Step 1: Create an HTML file, paste the below HTML code and execute it with any of your browsers.

HTML




<html>
  
<body>
    <script type="text/javascript">
        const xhr = new XMLHttpRequest();
        const url = 'http://localhost:3000/events';
        xhr.open('GET', url);
        xhr.send();
    </script>
</body>
  
</html>


Step 2: Open the DEVTOOLS by pressing F12 in your browser.

Step 3: Go to the console tab to see the CORS error message.

Step 4: Create a JS file with the below code:

Javascript




'use strict';
  
const express = require('express');
run().catch(err => console.log(err));
  
async function run() {
    const app = express();
    app.get('/events', async function (req, res) {
        res.send('Hi');
    });
    await app.listen(3000);
    console.log('Listening on port 3000');
}


Step 5: Run the below command in your command prompt:

$ node <file_name>.js

Output :

 

In the above example, we got a CORS policy error because we requested the resource with AJAX and the origin of such request is NULL which does not match with the server origin where the above JS file runs.

To prevent from acquiring this policy we send a special response header from the server end called “Access-Control-Allow-Origin” which is either set as “*” which means all origins are allowed or “<url>” which means only the specific URL is allowed.

The above JS file changes to Where we are assigning the Access-Control-Allow-Origin as “*” to prevent the CORS error:

Javascript




'use strict';
  
const express = require('express');
run().catch(err => console.log(err));
  
async function run() {
    const app = express();
  
    app.get('/events', async function (req, res) {
        res.set({ "Access-Control-Allow-Origin": "*" });
        res.send('Hi');
  
    });
  
    await app.listen(3000);
    console.log('Listening on port 3000');
}


Example 2: In this example, we will make a server to allow a null origin, the origin that represents the AJAX request. Hence, we are successfully able to console the string “Hello World”.

Step 1: Create an HTML file, paste the below HTML code and execute it with any of your browsers:

HTML




<html>
  
<body>
    <script type="text/javascript">
        const xhr = new XMLHttpRequest();
        const url = 'http://localhost:3000/events';
        xhr.onload = (res) => {
            console.log(res.target.response);
        }
        xhr.open('POST', url);
  
        xhr.send("Hello World!");
    </script>
</body>
  
</html>


Step 2: Open the DEVTOOLS by pressing F12 in your browser.

Step 3: Go to the console tab to see the CORS error message.

Step 4: Create a JS file with the below code:

Javascript




'use strict';
  
const express = require('express');
run().catch(err => console.log(err));
  
async function run() {
    const app = express();
  
    app.post('/events', (req, res) => {
        res.set({
            'Cache-Control': 'no-cache',
            'Access-Control-Allow-Origin': 'null'
        });
        req.on("data", (data) => {
  
            res.status(200)
            res.send(data.toString());
        })
  
    })
  
    await app.listen(3000);
    console.log('Listening on port 3000');
}


Step 5: Run the below command in your command prompt:

$ node <file_name>.js

Output:

 

Similarly, we will find various other situations of getting restricted by the CORS policy, like if a server of one origin lets say http://abc is requesting some other origin lets say http://xyz, then the origin abc cannot access origin xyz unless permitted by the origin xyz.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads