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

Viewed 2303

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[]'.
3 Answers

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

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"]

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

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