Home > Software design >  How to create an api dynamic route in Next.js?
How to create an api dynamic route in Next.js?

Time:03-31

I am trying to add a dynamic route to the api folder for GET request.
In this scenario it works fine
api/[product]

const baseUrl ='https://myUrl'
 const { product } = req.query
  const url = `${baseUrl}/${product}`

And then testing http://localhost:3000/api/phone in Postman returns the correct result. So far it is fine.
Then, instead of fetching the api by product, I want my dynamic property to be filter values.
Filter syntax provided by particular api looks like this ?$filter=name eq 'Milk'.
Filtering on frontend works fine when I test it in postman or in browser.

https://myUrl/phone?$filter=name eq 'iphone'

Now I try to do exactly the same as above, now in api folder. But it returns 404 This page could not be found..

api/[productType]

const baseUrl ='https://myUrl/phone?$filter'
 const { productType } = req.query
  const url = `${baseUrl}=${productType}`

In Postman I test it so:

`http://localhost:3000/api/phone=name-eq-'iphone'`

And get 404 response. How to fix this issue? Any help will be appreciated.

CodePudding user response:

I have created a demo at https://github.com/vercel-support/so-71663454-nextjs-route-poc with

// /api/[productType]

export default function handler (req, res) {
  const baseUrl ='https://myUrl/phone?$filter'

  const { productType } = req.query
  
  const url = `${baseUrl}=${productType}`
  res.json({ productType, query: req.query, url })
}

If you visit the link using https://so-71663454-nextjs-route-poc.vercel-support.app/api/phone=name-eq-'iphone'

You should be able to see the following result:

{
  "productType": "phone=name-eq-'iphone'",
  "query": {
    "productType": "phone=name-eq-'iphone'"
  },
  "url": "https://myUrl/phone?$filter=phone=name-eq-'iphone'"
}
  • Related