Skip to main content

Fetching External API Data

In this lesson you'll learn how to use data from an external API in your NextJS web app. For our example, we'll be using data from GitHub.

We'll be using https://api.github.com/orgs/dabblelab/repos

  1. Create a constant to hold the endpoint URL in index.js on line 3.

    const defaultEndpoint = 'https://api.github.com/orgs/dabblelab/repos';
  2. Create a function to return the serverSideProps

    export async function getServerSideProps() {
    const response = await fetch(defaultEndpoint);
    const data = await response.json();
    return {
    props: {
    data
    }
    }
    }
  3. Pass data into the Home function on line 15 of index.js

    export default function Home({ data }) {
    console.log('data', data);
    return (
    //code omitted for brevity
    )
    }

    Then refresh the page and use the devTools in Chrome to view the data logged to the console like the following screenshot shows.

    [screenshot goes here]

  4. Within the Home function in index.js Use the data in the page

    const { results = [] } = data;
  5. Use the results

    <div className={styles.grid}>
    {data.map(result => {
    const { id, name, description, html_url } = result;
    return (
    <a href={html_url} className={styles.card}>
    <h2>{name} &rarr;</h2>
    <p>{description}</p>
    </a>
    )
    })}
    </div>