Next.js API Routes: How to Get Parameters & Query String

Updated: January 14, 2023 By: Khue 4 comments

With Next.js, you can build your backend API right in the pages/api directory of your project. Suppose you want to fetch data about some fictional products from your database and send them to the client. To get a list of products, use this route:

/api/products

// add file: pages/api/products.js

If you have tons of products, it’s likely that you will need pagination. The backend will require information to paginate data; at least there should be the current page and the number of results per page ((in more complex cases, there is also sort order, sorting criteria, classification, etc.). Therefore, the client will send a GET request to /api/products with a query string like so:

/api/products?page=1&limit=10

To get page (the current page) and limit (the number of results per page), you can do as follows:

// pages/api/products.js
export default async function products(req, res) {
    const query = req.query;
    const { page, limit } = query;

    // use the information from the query to get the products
    // then send the data back to the client
}

To get detailed information about a single product, we use this dynamic route:

/api/products/[productId]

// add file: pages/api/products/[productId].js

To extract productId, you can do this:

// pages/api/products/[productId].js
export default async function poduct(req, res){
    const query = req.query;
    const { productId } = query;
    
    // use productId to retrieve the product from your database
    // then send this data back to the client
}

Make sure the file structure in your pages directory is similar to this:

The tutorial ends here. If you have any questions about what we’ve discussed, please leave a comment. Happy coding and have a nice day!

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments