5

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?

1 Answer 1

8

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.

4
  • Thanks for the answer! I don't really get how I'm supposed to make my page SEO friendly if it depends of data queried from the database... Am I supposed to use getServerSideProps? May 30, 2020 at 13:44
  • 1
    @Thanh-QuyNguyen, it depends on nature of the data. If it doesn't change often you can consider pre-render it at build time. getServerSideProps will fetch data on every request and pre-render it on the server side but the request time would increase as it's no longer statically rendered. May 31, 2020 at 5:36
  • Even with a getServerSideProps, I am still getting that error 500... Any idea why and how I can fix that? Jun 1, 2020 at 8:48
  • @Thanh-QuyNguyen, you can check Node.js console output in CLI / logs to see the exact error that caused error 500. Jun 1, 2020 at 11:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.