Thanh-Quy Nguyen
Thanh-Quy Nguyen

Reputation: 3235

API call in NextJS getStaticProps causes error 500

An API call made in getStaticProps seems to cause an error 500.

Here's my component's code:

import React from "react";
import API from "services/api";

const ArtistListPage = (props) => {
    return (
        <>
            {props.artists.map((artist) => (
                <div key={artist.id}>{artist.first_name}</div>
            ))}
        </>
    );
};

export async function getStaticProps() {
    // Get external data from the file system, API, DB, etc.
    const res = await API.get("/get_artists");
    const artists = await res.data.json();
    return {
        props: { artists },
    };
}

export default ArtistListPage;

I'd like to mention that the same API call in a useEffect works, as well as passing in a hard coded object to props in getStaticProps. Only the API call inside the getStaticProps seems to cause an issue.

Does anyone know where the error could come from and how to solve it?

Upvotes: 5

Views: 5289

Answers (1)

Nikolai Kiselev
Nikolai Kiselev

Reputation: 6603

getStaticProps is executed at a build time and you can't call your own API because Next.js server is not running.

You can execute DB queries or read from file system inside getStaticProps directly, without making an API call.

Upvotes: 9

Related Questions