Good question! The order of these checks generally depends on the intent and typical HTTP best practices, but in most cases you should check the HTTP method first, then the URL. Here's why:
- Checking the method first (e.g.,
req.method !== 'GET') means you can return a 405 Method Not Allowed immediately if the method is not supported, regardless of the URL. This aligns with the HTTP spec, where 405 means "the method is known by the server but not allowed for the specified resource."
- Checking the URL next (e.g.,
req.url !== endpoint) and returning a 404 Not Found means that for allowed methods, you can then confirm whether the resource exists.
Your current logic:
if (req.url !== endpoint) {
res.writeHead(404);
logger.debug('[PROMETHEUS] 404', requestSummary);
return res.end();
}
if (req.method !== 'GET') {
res.writeHead(405, { Allow: 'GET' });
logger.debug('[PROMETHEUS] 405', requestSummary);
return res.end();
}
This means:
- If the URL isn't the endpoint, respond
404 (not found), regardless of the method.
- If the URL matches but the method isn't GET, return
405.
That's reasonable, but per the HTTP spec and best practices, it can be better to check method first:
if (req.method !== 'GET') {
res.writeHead(405, { Allow: 'GET' });
logger.debug('[PROMETHEUS] 405', requestSummary);
return res.end();
}
if (req.url !== endpoint) {
res.writeHead(404);
logger.debug('[PROMETHEUS] 404', requestSummary);
return res.end();
}
Why?
- Let's assume a client sends
POST /unknown-endpoint. With your original code, they get 404 because the URL doesn't match, ignoring the method. With method-first checking, you respond 405 Method Not Allowed because POST is not an allowed method — which is arguably more informative: the resource doesn't allow the method, even if the resource doesn't exist.
- However, the HTTP specification notes that if the resource does not exist,
404 Not Found is the correct response — and the Allow header should only be sent if the resource exists but the method is not allowed.
Therefore, based on RFC 7231 Section 6.5.5:
The 405 (Method Not Allowed) status code indicates that the method received in the request-line is known by the origin server but not supported by the target resource.
If the resource doesn't exist (404), method (allowed or not) does not matter.
Summary:
- If you want to be strictly specification-compliant, check URL (resource existence) first, then validate method.
- Your current order is consistent with that.
So your current order is correct if you want to distinguish:
- If resource does not exist →
404
- Else if method not allowed →
405
If you want to respond with 405 for all wrong methods regardless of the resource's existence, flip the order, but that is less usual.
In conclusion: Your current code is correct and probably better (and more standard). You do not need to swap their order.