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

247
Visualizações
Why use Next.js API route with an external API?

I am new in Next.js. I want to know what is the use of export default function handler because we can directly call the API using fetch.

In my HTML code I put below code. When I click on submit button sendformData() function will be called.

<input type="button" value="Submit" onClick={() => this.sendformData()} ></input>
sendformData = async () => {
    const res = await fetch("/api/comments/getTwitFrmUrl?twitUrl=" + this.state.twitUrl, {
      headers: {
        "Content-Type": "application/json",
      },
      method: "GET",
    });

    const result = await res.json();
    this.setState({ data: result.data });
  };

When sendformData function is called, it calls /api/comments/ file and calls the function.

enter image description here

Here is the /api/comments/[id].js file code.

export default async function handler(req, res) {
  if (req.query.id == 'getTwitFrmUrl') {
    const resData = await fetch(
      "https://dev.. .com/api/getTwitFrmUrl?twitId=" + req.query.twitUrl
    ).then((response) => response.text()).then(result => JSON.parse(result).data);

    res.status(200).json({ data: resData });
  }
  else if (req.query.id == 'getformdata') {
    console.log('getformdata api');
    res.status(200).json({ user: 'getuserData' });
  }
}

When I put the below code in the sendformData same response will be retrieved. So why we need to call export default function handler function?

 sendformData = async () => {
    const res = await fetch(
          "https://dev.. .com/api/getTwitFrmUrl?twitId=" + req.query.twitUrl
        ).then((response) => response.text()).then(result => JSON.parse(result).data);

    const result = await res.json();
    this.setState({ data: result.data });
  };
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you already have an existing API there's no need to proxy requests to that API through an API route. It's completely fine to make a direct call to the API.

However, there are some use-cases for wanting to do so. From the API routes documentation:

  • Masking the URL of an external service (e.g. /api/secret instead of https://company.com/secret-url)
  • Using Environment Variables on the server to securely access external services.

Essentially, for security reasons, if you want to hide the external API URL, or want to avoid exposing environment variables needed for a request to the browser.

You may also want proxy requests through API routes to circumvent CORS restrictions. By making the requests to the external API from the server CORS will not be applied.

about 4 years ago · Juan Pablo Isaza Relatório
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