nextjs call api

nextjs

To make an API call in Next.js, you can use fetch or a library like axios.

Here’s an example of making a GET request to an API using fetch in a Next.js server-side function:

import fetch from 'isomorphic-unfetch'

export default async function getData(req, res) {
  const response = await fetch('https://my-api.com/endpoint')
  const data = await response.json()
  return { data }
}

You can then call this function in a page component to retrieve the data from the API and render it:

import getData from '../lib/getData'

function MyPage(props) {
  return (
    <div>
      {props.data.map(item => (
        <p key={item.id}>{item.name}</p>
      ))}
    </div>
  )
}

MyPage.getInitialProps = async function() {
  const data = await getData()
  return data
}

Alternatively, you can use a library like axios to make the API call. Here’s an example using axios in a page component:

import axios from 'axios'

function MyPage(props) {
  return (
    <div>
      {props.data.map(item => (
        <p key={item.id}>{item.name}</p>
      ))}
    </div>
  )
}

MyPage.getInitialProps = async function() {
  const response = await axios.get('https://my-api.com/endpoint')
  const data = response.data
  return { data }
}

It’s also possible to make API calls in the client-side of your Next.js app, but be aware that the client-side code will be run in the user’s browser, so you should take care to avoid exposing sensitive data or making unsecured requests.