Your query string says page=undefined

Your query string says page=undefined and nothing in your app noticed. Here is a bug I have shipped more than once, and I have seen it in other people’s code often enough to stop feeling bad about it.
You build a URL for a list screen. Page number, a search box, maybe a filter or two:
const params = new URLSearchParams({
page: currentPage,
q: searchText,
status: selectedStatus,
})
fetch(`/api/products?${params}`)It works. Nothing throws. Your browser’s network tab shows a request going out with a query string attached, and the response comes back as a clean 200. Then a bug report lands saying the list is empty when nobody has typed anything into the search box, you open the server logs, and you find this:
GET /api/products?page=undefined&q=undefined&status=undefinedNot missing. Not empty. The literal nine-letter word undefined, three times across three filters, sent to your API as if it were a real value a user had chosen.
Why it happens
URLSearchParams has one job and it does it honestly: it turns things into text. Every value you hand it goes through the same conversion a template string would do, because that is what the URL spec says should happen. There is no “skip this one” rule, and there was never meant to be one. From its point of view there is nothing to skip. You gave it a key and a value, so it wrote down a key and a value.
Run this in Node, or paste it into your browser console, and watch what comes back:
new URLSearchParams({ page: undefined, status: null, q: "x" }).toString()
// 'page=undefined&status=null&q=x'undefined became the nine-letter word. null became the four-letter one. Both are now strings your backend has to make sense of, and parseInt("undefined") is NaN, which is exactly how a product list ends up empty with no error anywhere to explain it.
It gets quieter, and worse, with objects:
new URLSearchParams({ filter: { category: "shoes" } }).toString()
// 'filter=%5Bobject+Object%5D'That decodes back to the string [object Object]. Your filter object did not get serialised. It got stringified, which is a different thing, and nothing anywhere warned you about the difference. If you need to send structured data in a query string you have to encode it yourself, usually as JSON, and decode it deliberately on the other side.
The array one that bites hardest
This is the one I most want you to remember, because unlike the others it genuinely looks like it worked.
new URLSearchParams({ tags: ["a", "b"] }).toString()
// 'tags=a%2Cb'That %2C is a comma. Most APIs that accept a list expect the key to repeat instead: tags=a&tags=b. What you actually sent is a single tags value whose text happens to have a comma sitting in the middle of it. The proof is on the receiving end:
new URLSearchParams("tags=a%2Cb").getAll("tags")
// [ 'a,b' ] ← one item, not twoOne item. A server that calls getAll and expects two tags gets a single tag named a,b, which matches no row in any table, so the filtered list comes back empty and everybody spends the afternoon blaming the database.
Proving it against a real server
I did not want to trust my own reading of the spec on this, so I wrote a tiny Node server, fired the naive query string at it, and printed exactly what arrived. No framework, no mocking library, no test harness pretending to be a network. A real socket and a real request:
import { createServer } from 'node:http'
const server = createServer((req, res) => {
const url = new URL(req.url, 'http://localhost')
console.log('raw :', req.url)
console.log('page:', url.searchParams.get('page'))
console.log('q :', url.searchParams.get('q'))
console.log('tags:', url.searchParams.getAll('tags'))
res.end('ok')
})
await new Promise(r => server.listen(0, r))
const params = new URLSearchParams({
page: undefined,
q: 'red shoes',
tags: ['a', 'b'],
})
await fetch(`http://localhost:${server.address().port}/s?${params}`)
server.close()Output, on Node 22.16.0:
raw : /s?page=undefined&q=red+shoes&tags=a%2Cb
page: undefined
q : red shoes
tags: [ 'a,b' ]Notice that the space inside red shoes travelled across the wire as a plus sign rather than as %20. That is correct and completely normal for a query string, and searchParams.get turns it back into a space for you on arrival. But it only works if whatever reads the query string on the other side plays by the same rule. A hand-rolled parser does not:
decodeURIComponent('red+shoes')
// 'red+shoes' ← the plus survives, as a plusSo if your backend splits the URL itself and reaches for decodeURIComponent, then every search for two words arrives with a + jammed into the middle of it, and your LIKE query finds nothing. If it uses a real query parser instead — req.query in Express, url.searchParams in plain Node, whatever helper your framework ships — you get the space back and everything is fine. It is worth spending two minutes checking which of those your API actually does before you spend an afternoon on the symptom.
The fix everyone writes, and the second bug it creates
The natural reaction, once you have seen page=undefined in a log, is to strip the empty stuff out before building the string:
// looks fine. is not fine.
const clean = Object.fromEntries(
Object.entries(params).filter(([, v]) => v)
)That filter asks one question: is this value truthy. And in a real list screen there are at least four perfectly meaningful values that are all falsy:
const params = { page: 0, inStock: false, q: '', status: undefined }
new URLSearchParams(
Object.fromEntries(Object.entries(params).filter(([, v]) => v))
).toString()
// '' ← all four gonePage zero is a real page, usually the first one. “Out of stock only” is a real choice that a user clicked on purpose. An empty search box is a real instruction too, and what it means is show me everything. The truthy filter threw away all three of those in order to get rid of one undefined.
This second version of the bug is harder to catch than the first, which is why I think it is the more dangerous of the two. Nothing silly shows up in the logs. The parameter is simply absent, the server falls back to whatever its default is, and the page renders something plausible. You will not find it by reading the network tab. You will find it when a user insists they ticked a box and the results did not change.
You only ever want to drop two values: undefined and null. That is precisely what == null tests for, and this is the one place I will cheerfully use loose equality, because it catches both of them at once and nothing else. Writing it the strict way takes two comparisons to say the same thing.
function toQuery(params) {
const search = new URLSearchParams()
for (const [key, value] of Object.entries(params)) {
if (value == null) continue
for (const item of Array.isArray(value) ? value : [value]) {
search.append(key, String(item))
}
}
return search
}
toQuery({ page: 0, inStock: false, q: '', status: undefined, tags: ['a', 'b'] }).toString()
// 'page=0&inStock=false&q=&tags=a&tags=b'Eight lines, four of which do real work, and every case above now comes out right. page=0 survives. inStock=false survives. The empty search box arrives as an empty value instead of vanishing. status is gone, because it genuinely had nothing to say. And tags repeats, the way list parameters are supposed to, so getAll on the server hands back two items rather than one stuck-together string.
If your API prefers comma-joined lists over repeated keys, that is a completely reasonable choice — plenty of APIs do it. Just make it on purpose with search.append('tags', value.join(',')), so that the next person reading the code can tell it was a decision and not an accident.
How to check your own code in five minutes
Search your project for new URLSearchParams( and look at what gets passed in. If the argument is an object literal built from form state, component props, or a function’s optional arguments, there is a good chance something in it is undefined right now. Three places this shows up most often in my own work:
- Optional function arguments. A helper signed
listProducts(page, status)called aslistProducts(2)has astatusofundefined, and that goes straight into the query string unless something stops it. - Form state before first input. A field initialised as
undefinedrather than''sends the word until the user types into it, which is why the bug so often reproduces on a fresh page load and nowhere else. - Optional chaining in the middle of a chain.
user?.filters?.categoryisundefinedwhenever either half is missing, and reads so naturally that it rarely gets a second look.
The quickest confirmation is to log the finished string, not the object you built it from. console.log(params.toString()) tells you the truth in one line; inspecting the source object just shows you what you intended.
What I actually took from this
All of these problems come from one wrong assumption: that URLSearchParams knows what an “empty” value is. It does not, and it was never trying to. It converts values to text, faithfully, including the values you did not mean to send. The judgement about what counts as nothing belongs to you, and the only honest place to make it is before the value reaches the query string at all. The MDN reference is clear that values are stringified; it just does not spell out how expensive that is in practice.
The reason this one earns fifteen minutes of your attention is that it fails politely. No stack trace, no red text in the console, no failed request to catch in an error handler. You get a 200 back and a list that is empty, or a page of results that quietly ignored the filter a user picked. Those are the bugs that live in a codebase for a year.
It belongs to the same family as one leading slash deleting half your API base URL, an object reordering itself the moment its keys are numbers, and the cached 404 that came back as a success: small, well-documented behaviours doing exactly what the spec says, in a place where your code quietly assumed something kinder.