'How to use query params in Next.js?

In my Next.js API functions like:

export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
  const { someQueryParam } = req.query;
  doSomething(someQueryParam);
  ...

I see TypeScript error:

Argument of type 'string | string[]' is not assignable to parameter of type 'string'. Type 'string[]' is not assignable to type 'string'.ts(2345)

So I've started using this helper function I wrote:

export function getSimpleStringFromParam(paramValue: string | string[] | undefined) {
  if (paramValue) {
    return typeof paramValue === 'string' ? paramValue : paramValue[0];
  } else {
    return '';
  }
}

It works fine, but it feels ugly and weird and feels like what I'm trying to do would be such a common need that Next.js or Node would handle it more smoothly. So I feel like I'm misunderstanding something.

Is there a more official / better way to pluck simple string values out of the query params?



Solution 1:[1]

I look at your helper function and see that someQueryParam is string

export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
  const someQueryParam: string = req.query.someQueryParam
    ? req.query.someQueryParam as string
    : "";
  doSomething(someQueryParam);
}

But if you need get string | string[] use that:

export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
  const someQueryParam: string | string[] = req.query.someQueryParam
    ? req.query.someQueryParam
    : "";
  doSomething(someQueryParam);
}

OR

 export default async function handler(req: NextApiRequest, res: NextApiResponse<any>) {
  const { someQueryParam } = req.query.someQueryParam
    ? req.query
    : { someQueryParam: "" };
  doSomething(someQueryParam);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 GoSSy4691