Origin
Description
The Origin request header is an HTTP header field used to indicate the origin
(scheme, host, and port) of the request. It is primarily used in Cross-Origin
Resource Sharing (CORS) and security contexts to help servers determine whether
a request is allowed based on the requesting origin.
Unlike the Referer header, which provides the full URL of the previous page,
the Origin header only includes the essential information needed for security
policies, reducing the risk of leaking sensitive details.
The Origin header is commonly included in requests made via JavaScript (e.g.,
fetch and XMLHttpRequest) when performing cross-origin resource sharing, as
well as in HTTP methods that might modify server-side data (e.g., POST, PUT,
DELETE).
Syntax
The Origin header follows this syntax:
For example:
If a request originates from a subdomain or a different port, the header might look like this:
Examples
Basic Usage in HTTP Requests
When a browser makes a cross-origin request using JavaScript, the request will
include an Origin header:
POST /api/data HTTP/1.1
Host: api.example.com
Origin: https://www.example.com
Content-Type: application/json
{"key": "value"}
The server can inspect the Origin header and decide whether to allow the request.
Server-Side Handling
A server handling CORS requests can check the Origin header and respond
accordingly. Here’s an example using Node.js with Express:
const express = require('express');
const app = express();
app.use((req, res, next) => {
const allowedOrigins = ['https://www.example.com', 'https://app.example.com'];
if (allowedOrigins.includes(req.headers.origin)) {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
}
next();
});
app.get('/data', (req, res) => {
res.json({ message: 'CORS request received' });
});
app.listen(3000, () => console.log('Server running on port 3000'));
Client-Side Example with Fetch API
A JavaScript client can make a cross-origin request using fetch, which will
automatically include the Origin header:
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Summary
The Origin request header is an essential security feature that helps servers
enforce cross-origin policies. It allows servers to determine where requests
originate and decide whether to permit or block them. Used mainly in CORS and
security-sensitive operations, the Origin header is a fundamental part of
modern web application security and access control.