Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

273
Visualizações
Next.js: filter on rest api url doesn't work when the route is a dynamic api route

I am trying to implement filter on API before fetching.
I have a dynamic API route([productType]), which works fine. But when I try to filter the API, it doesn't work. So the syntax for filtering API looks like this ?$filter=name eq 'Milk' and adding this to the url doesn't work.
As in docs says, I have a tried to change the filename like this [...productType] or [[...productType]] but none of them helps.
It returns the api data without filtering. Here is my code in API dynamic route[productType]. pages/api/[productType]

import axios, { AxiosRequestConfig, Method } from 'axios'
import { pick } from 'lodash'
import { NextApiRequest, NextApiResponse } from 'next'
const baseUrl ='https://myUrl...'

const getFromAPIServer = async (
  req: NextApiRequest,
  res: NextApiResponse,
) => {
  const { productType } = req.query
  const param = req.query.params //here  I tried to add the parameter for filter, which doesn't work
  const url = `${baseUrl}/${productType}?${param}?`
  const method = req.method as Method
  const { body } = req

  const allowedHeaders = ['If-Match']
  const headers = pick(req.headers, allowedHeaders) as Record<string, string>

  try {
    const request: AxiosRequestConfig = {
      method,
      url,
      headers: {
        ...headers,
        Authorization: `Basic ${process.env.TOKEN}`,
        'Content-Type': 'application/json',
      },
    }
    if (method !== 'GET' && body) {
      request.data = body
    }
    const { data } = await axios.request(request)
    res.status(200).json(data)
  } catch (error) {
    if (!axios.isAxiosError(error)) {
      throw error
    }
    // Return AxiosError to the client
    res.status(error?.response?.status || 500).json(error?.response?.data)
  }
}

export default getFromAPIServer

And in components I have the fetching function where I try to fetch the api with filter

export const getApiRequest = (url: string) => {
  const { data } = useQuery(['key', url], async () => {
    const response = await fetch(url, {
      method: 'get',
    })
    if (!response.ok) throw new Error(response.statusText)
    return await response.json()
  })

  return { data }
}

 const { data } = getApiRequest(`${productTypeUrl}?$filter=name eq 'Milk'`) 

Forgot to mention: In Postman filtering, the API works fine. It works also fine when I try to fetch with the filter url in components, not importing from api folder.

Update

Doing the filtering in api folder works as below

const url = `${baseUrl}/${productType}?$filter=name eq 'Milk'?`

However, this is not what I want. I want to have filter as params on API folder, like productType so that I can use it on client side.

Any help will be appreciated

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda