I was reviewing some code and I saw something like this:
if (result.indexOf('?') === -1) {
result += '?';
}
result += '&' + SOMETHING;
Clearly this can result in an URL like this http://example.com?&a=b
The author of the code sees nothing unusual in the code but ?& bothers me. I could not find any restrictions in the RFC for URI to prove him wrong (or maybe I missed it).
Clearly in the network tab of Chrome dev tools it appears as an empty pair:
Should URL like this bother me or am i just paranoid?
This case will be interpreted as an empty value by most servers, so yes, it is indeed valid. What's going to happen is that the server checks between ?
and every &
and then separates the values at =
accordingly.
So when there is nothing between a ?
and a &
(or two &
's), the values will both be empty. Missing =
's will affect whether the value is "" or null, but it will not make the query invalid.
Watch out with this, because some parsers might not find this to be valid, so you may get problems when using custom parsers (in JavaScript for example).
I wrote up a blog post about some of these edge cases years ago.
tl;dr: yes, ?&example
is valid
What's important about it is that you're defining a key of ""
with a value of null
.
You can pretty much guarantee that almost no libraries support those empty string keys, so don't rely on them working, but as far as having a URL along the lines of ?&foo=bar
, you should be fine when accessing the foo
key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With