tatethurston / nextjs-routes

Type safe routing for Next.js
MIT License
580 stars 21 forks source link

bug: undefined query parameters are added to URLSearchParams #206

Closed sleepdotexe closed 5 days ago

sleepdotexe commented 1 week ago

Describe the bug When using the route() function, undefined values in the query object are added to the URLSearchParams as param=undefined.

A simple example:

const possibleQueryParam1: string | undefined = "param1";
const possibleQueryParam2: string | undefined = undefined;

return (
  <Link
    href={route({
      pathname: "/",
      query: {
        param1: possibleQueryParam1,
        param2: possibleQueryParam2,
      },
    })}
  >
    Go home
  </Link>
);

This is maybe open to discussion, but I would expect that the link would have an href of /?param1=param1 given that there is no actual value for param2. However in reality, the href is /?param1=param1&param2=undefined.

It would make more sense to me for the route() function to automatically strip any undefined values, forcing the user to explicity include them by converting them to a string. Otherwise, any time I am including a dynamic value that may be undefined, I have to do a conditional check to ensure it doesn't get included in the href.

Taking a look at the code, this could likely be easily solved here by including a check to ensure that value is actually defined.

Something like this I think should work:

  const search = new URLSearchParams();
  for (const key in r.query) {
    if (!params.has(key)) {
      const value = r.query[key];
+     if(value === undefined) continue;
      if (Array.isArray(value)) {
        value.forEach((val) => search.append(key, val));
      } else {
        search.append(key, value as string);
      }
    }
  }

Context (please complete the following information):

tatethurston commented 1 week ago

Thanks for reporting @sleepdotexe. That's what I get for using a cast 😆