logo
podcast Podcast
get help Get Unstuck

Stick with dashes in HTTP headers

And avoid underscores

Joel Clermont
Joel Clermont
2025-01-16

When designing an API, and documenting it in a spec, I like to use names with underscores for path parameters, query strings, and body payloads. user_id looks nicer to me than user-id. It's just a personal preference, both work fine as far as Laravel is concerned.

Initially, on this API, I did the same thing for some custom headers, like tenant_id, but I ran into an issue.

When I was trying to validate my spec with this package, it kept failing saying that tenant_id was missing.

When I dumped out the request in my test, I could definitely see the tenant_id header, but when I dumped it inside the validator package, the header was now appearing as tenant-id.

This is exactly the time I break out my step debugger to figure out what is happening. As I stepped through the code, I could see when the Laravel request was being created and parsed, header names were being stuffed into $_SERVER variables, like TENANT_ID, and then when they were read back out, they were getting named as tenant-id.

Instead of digging deeper and trying to fight this behavior, I paused and thought about it. Have I ever seen an HTTP header with an underscore? Scour MDN and you will not find one. They all have dashes.

So then I looked at various RFCs defining HTTP behavior, and tucked away in RFC 9110 Section 16.3.1 I see this:

It MUST conform to the field-name syntax defined in Section 5.1, and it SHOULD be restricted to just letters, digits, and hyphen ('-') characters, with the first character being a letter.

There you go! This conversion was being done to conform to the spec. Problem solved, I changed my header to have dashes, and everything worked as expected.

Here to help,

Joel

P.S. How confident are you in your app's validation rules? We've assembled a comprehensive guide to getting the most out of your validation logic.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.