Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 826
Basit Minhas Avatar asked Dec 03 '25 16:12

Basit Minhas


2 Answers

To get the search parameters you can simply use req.nextUrl.searchParams.get("keyword")

async function GET(req:NextRequest){
 console.log(req.nextUrl.searchParams.get("keyword"))
}
like image 73
theshubhagrwl Avatar answered Dec 05 '25 04:12

theshubhagrwl


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

like image 37
mahieyin-rahmun Avatar answered Dec 05 '25 06:12

mahieyin-rahmun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!