Security Recommended
Refuse odd requests from other sites
Browsers send Sec-Fetch-* headers that say where a request came from. Use them to refuse cross-site requests that are not normal page visits.
How to do it
In middleware, allow requests with no Sec-Fetch-Site, or with same-origin, same-site or none. Also allow cross-site GET navigations, except into object or embed. Answer 403 to the rest. Exempt public APIs and files meant for other sites.
Example
function fetchMetadata(req, res, next) {
const site = req.get('Sec-Fetch-Site');
if (!site || ['same-origin', 'same-site', 'none'].includes(site)) return next();
const dest = req.get('Sec-Fetch-Dest');
if (req.method === 'GET' && req.get('Sec-Fetch-Mode') === 'navigate' && dest !== 'object' && dest !== 'embed') return next();
res.status(403).end();
}
How to check
A cross-site fetch to a page fails with 403. A normal link still works.
For agents: if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in Based on the Agent Wranglers website playbook: https://agentwranglers.se/playbook/website/security/fetch-metadata.