'Why are Next.js' req.query object's values of type string | string[]?

Next.js' API Routes receive a req object - it's an extension of http.IncomingMessage with additional middlewares such as req.query. The typing of req.query, found in their utils.ts, is:

query: {
    [key: string]: string | string[]
}

Why is it possible to receive an array of strings from the query?

I'm trying to perform string methods on my query values but run into TS errors -_-

someString.split() // => Property 'split' does not exist on type 'string | string[]'.


Solution 1:[1]

I think we can use this, if we don't work with more than one param with the same name:

const id = req.query.id as string

Solution 2:[2]

You can convert 'string | string[]' to 'string' by joining them like this:

let { param } = req.query.param;
if (Array.isArray(param)) {
  param = param.join('');
}

Solution 3:[3]

the query object is of type string | string[] because of catch all routes https://nextjs.org/docs/routing/dynamic-routes

if you had a file that was named [id].js and used the url pages/123, router.query would return a string 123, but if the file was named [...id].js and used the url pages/123 it would be a catch all route and would return an array ["123"], if the url were pages/123/456 it would return ["123", "456"]

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 Bruno Yuzo
Solution 2 Kamran Ansari
Solution 3 Bijay Bohora