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

Last updated on June 2, 2022 Pennywise Loading... Post a comment

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 fiction 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 and limit, 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 the 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. Further reading:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like