JAVASCRIPT
Set a Strict Referrer-Policy for Enhanced Privacy and Security
Enhance user privacy and reduce information leakage by implementing a strict Referrer-Policy HTTP header, controlling how referrer information is sent.
const express = require('express');
const helmet = require('helmet');
const app = express();
// Use Helmet to set security headers, including Referrer-Policy
// We explicitly configure Referrer-Policy here, overriding Helmet's default if needed
app.use(helmet({
referrerPolicy: { policy: 'no-referrer' } // Most restrictive: no referrer information is sent
// Alternative secure policies:
// referrerPolicy: { policy: 'same-origin' } // Only send referrer for same-origin requests
// referrerPolicy: { policy: 'strict-origin-when-cross-origin' } // Send full URL for same-origin, origin only for cross-origin HTTPS -> HTTPS/HTTP, no referrer for HTTP -> HTTP
}));
// Manual setting alternative (if not using Helmet or for extremely fine-grained control)
/*
app.use((req, res, next) => {
res.setHeader('Referrer-Policy', 'no-referrer'); // Example: 'no-referrer' or 'strict-origin-when-cross-origin'
next();
});
*/
app.get('/', (req, res) => {
res.send('Referrer-Policy header is set!');
});
// Example for a link from this page to another site
app.get('/external-link', (req, res) => {
// When the user clicks a link to an external site from this page,
// the Referrer-Policy will dictate how much referrer info is sent.
res.send('<p>Click <a href="https://www.example.com" target="_blank">here</a> to visit Example.com.</p>');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running with Referrer-Policy on port ${PORT}`);
});
How it works: The `Referrer-Policy` HTTP header controls how much referrer information (the origin or full URL of the page making a request) should be included with requests. A strict policy enhances user privacy and mitigates security risks like sensitive data leakage via referrer headers. This Node.js (Express) snippet demonstrates setting the `Referrer-Policy` using `helmet`. Setting it to `no-referrer` ensures no referrer information is sent at all. `strict-origin-when-cross-origin` is another strong option, sending the full URL for same-origin requests but only the origin for cross-origin requests, or nothing if the security protocol downgrades (HTTPS to HTTP).