Integrating Third-Party APIs in Next.js

Reading Time: 9 min read

Introduction

Incorporating third-party APIs into your Next.js applications can significantly enhance functionality and user experience. Whether you're fetching weather data, integrating social media feeds, or connecting to payment gateways, APIs provide a wealth of resources and capabilities. In this post, we'll explore how to effectively integrate third-party APIs into your Next.js projects, ensuring seamless and efficient data handling.

Setting Up Your Next.js Project

  1. Create a New Next.js App:

    Start by setting up a new Next.js application if you don't have one already.

    npx create-next-app third-party-api-app
    cd third-party-api-app
  2. Install Necessary Dependencies:

    Depending on the API you plan to use, you might need additional packages. For instance, if you’re working with REST APIs, the axios library is a great choice.

    npm install axios

Fetching Data from a Third-Party API

For this example, let's integrate a simple weather API to fetch and display current weather information.

  1. Create an API Key:

    Sign up for a weather API service like OpenWeatherMap and obtain an API key.

  2. Create an API Route in Next.js:

    Next.js allows you to create API routes that can serve as a backend for your frontend. Create a new file at pages/api/weather.js.

    // pages/api/weather.js
    import axios from 'axios'
     
    export default async (req, res) => {
      const { city } = req.query
      const apiKey = process.env.OPENWEATHER_API_KEY
      const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`
     
      try {
        const response = await axios.get(apiUrl)
        res.status(200).json(response.data)
      } catch (error) {
        res.status(500).json({ error: 'Failed to fetch weather data' })
      }
    }
  3. Fetch Data on the Client Side:

    Use the Next.js getServerSideProps function to fetch data from your API route and pass it to your component.

    // pages/index.js
    import { useState } from 'react'
    import axios from 'axios'
     
    export default function Home({ initialWeather }) {
      const [weather, setWeather] = useState(initialWeather)
      const [city, setCity] = useState('')
     
      const fetchWeather = async () => {
        const response = await axios.get(`/api/weather?city=${city}`)
        setWeather(response.data)
      }
     
      return (
        <div>
          <h1>Weather App</h1>
          <input
            type="text"
            value={city}
            onChange={(e) => setCity(e.target.value)}
            placeholder="Enter city"
          />
          <button onClick={fetchWeather}>Get Weather</button>
          {weather && (
            <div>
              <h2>{weather.name}</h2>
              <p>{weather.weather[0].description}</p>
              <p>{(weather.main.temp - 273.15).toFixed(2)}°C</p>
            </div>
          )}
        </div>
      )
    }
     
    export async function getServerSideProps() {
      const response = await axios.get(
        `http://localhost:3000/api/weather?city=London`,
      )
      return {
        props: {
          initialWeather: response.data,
        },
      }
    }

Handling Errors and Edge Cases

When working with third-party APIs, it's crucial to handle errors gracefully and account for various edge cases, such as network failures or invalid responses.

  1. API Error Handling:

    Update your API route to handle errors more robustly.

    // pages/api/weather.js
    import axios from 'axios'
     
    export default async (req, res) => {
      const { city } = req.query
      const apiKey = process.env.OPENWEATHER_API_KEY
      const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`
     
      try {
        const response = await axios.get(apiUrl)
        res.status(200).json(response.data)
      } catch (error) {
        if (error.response) {
          res
            .status(error.response.status)
            .json({ error: error.response.data.message })
        } else if (error.request) {
          res.status(500).json({ error: 'No response received from the API' })
        } else {
          res.status(500).json({ error: 'Failed to fetch weather data' })
        }
      }
    }
  2. Client-Side Error Handling:

    Update your client-side code to handle API errors.

    // pages/index.js
    import { useState } from 'react'
    import axios from 'axios'
     
    export default function Home({ initialWeather }) {
      const [weather, setWeather] = useState(initialWeather)
      const [city, setCity] = useState('')
      const [error, setError] = useState(null)
     
      const fetchWeather = async () => {
        try {
          const response = await axios.get(`/api/weather?city=${city}`)
          setWeather(response.data)
          setError(null)
        } catch (err) {
          setError(
            err.response
              ? err.response.data.error
              : 'Failed to fetch weather data',
          )
        }
      }
     
      return (
        <div>
          <h1>Weather App</h1>
          <input
            type="text"
            value={city}
            onChange={(e) => setCity(e.target.value)}
            placeholder="Enter city"
          />
          <button onClick={fetchWeather}>Get Weather</button>
          {error && <p style={{ color: 'red' }}>{error}</p>}
          {weather && !error && (
            <div>
              <h2>{weather.name}</h2>
              <p>{weather.weather[0].description}</p>
              <p>{(weather.main.temp - 273.15).toFixed(2)}°C</p>
            </div>
          )}
        </div>
      )
    }
     
    export async function getServerSideProps() {
      const response = await axios.get(
        `http://localhost:3000/api/weather?city=London`,
      )
      return {
        props: {
          initialWeather: response.data,
        },
      }
    }

Conclusion

Integrating third-party APIs into your Next.js applications can greatly enhance functionality and user experience. By following the steps outlined in this post, you can seamlessly fetch and display data from external sources, handle errors gracefully, and provide valuable features to your users. Start exploring the vast array of APIs available and see how they can transform your web applications.

For more detailed information, visit the Next.js documentation on API routes.

Go back Home.