javascriptreactjsnext.jsquery-string

How can I create API end point in Next.js with query string


I need to create the following API end point using Next.js:

/api/products/[name]?keyword=${anykeyword}.

I know I need to create it inside pages/api/products/[name] directory in index.js. But how can I access keyword.

req.query only contains name.

following is my code:

import { connectToDatabase } from "../../../../util/mongodb";
import validate from "../../../../validation/product";
//capitalize first letter only to avoid errors
import capitalize from "lodash.capitalize";

export default async function productsHandler(req, res) {
const {
  query: { name, keyword }, // here i cannot access keyword//
  method,
} = req,
Name = capitalize(name),
{ db } = await connectToDatabase(),
searchCriteria = keyword ? keyword : "price";

switch (method) {
case "GET":
  // @route GET api/products/[name]
  // @desc get products of [name] from data base
  // @access public
  {
    const products = await db
      .collection("products")
      .find({ category: Name })
      .sort({ [searchCriteria]: 1 })
      .toArray();

    if (!products.length)
      return res.status(404).json({ error: "no such category" });

    res.status(200).json(products);
  }

  break;

Solution

  • It probably has to do with how the request is being sent to the server side from the client. You probably need to revise that. I just tried out the example using Postman, and it correctly parsed the parameters:

    import { NextApiRequest, NextApiResponse } from "next";
    
    export default async (request: NextApiRequest, response: NextApiResponse) => {
      const {
        query: { name, keyword },
        method,
      } = request;
      console.log(name, keyword, method);
    
      // do nothing fancy and simply return a string concatenation
      return response.status(200).json({ query: name + " " + keyword });
    };
    
    

    Postman:

    enter image description here