How can I check on a server (cloudflare worker) that a http request is coming from a web browser, rather than something like curl - are there headers I can check, or is there a better way?
ChatGPT recommends:
addEventListener('fetch', (event) => {
const userAgent = event.request.headers.get('User-Agent');
if (userAgent && userAgent.includes('Mozilla') && userAgent.includes('AppleWebKit')) {
// Request is likely from a web browser
// Handle the request accordingly
} else {
// Request is not from a common web browser
// Handle it differently or deny access
}
});
However is that bulletproof, is there a better way? Does cloudflare provide its own headers I can check?
Here is what I went with:
request.headers.get('Accept').includes('html')
As the purpose of why I wanted such a check, is to send plaintext to things like curl/wget/etc (which don't send an Accept header by default), and to send a redirect to a html page for web browsers (which send an Accept header that accepts html).