How to get URL query string in API route in Next.js?

Viewed 812

I have a constant that uses the request query to pull into my API the name and town values of the URL parameters.

This works great. What I can't work out, I've looked at a number of articles but I want to return the full set of parameters from the URL, either as an array or a string. If it includes the URL path it's no problem, ideally just the parameters ampersand separated or any other way.

I need to do so as this API captures a set of question responses that may change over time, and I need the flexibility to loop over all the answers returned irrelevant if its 10 or 100.

export default async function (req, res) {
    const {
        query: name ,
        query: town ,
    } = req
    // ...
}
1 Answers

You can access the query params as a string from req.url which contains the full URL including the query params.

export default async function (req, res) {
    console.log(req.url) // Logs: '/api/info?name=john&town=london'
}

For more details on the req object check Node.js official documentation.


Alternatively, you can also get the query params as an object from the req.query object, which you can manipulate however you like.

export default async function (req, res) {
    console.log(req.query) // Logs: { name: 'john', town: 'london' }
}
Related