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?

Thanh-Quy Nguyen
  • 2,995
  • 7
  • 30
  • 46

1 Answers1

9

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.

Nikolai Kiselev
  • 6,201
  • 2
  • 27
  • 37
  • 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`? – Thanh-Quy Nguyen May 30 '20 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. – Nikolai Kiselev May 31 '20 at 05:36
  • Even with a `getServerSideProps`, I am still getting that error 500... Any idea why and how I can fix that? – Thanh-Quy Nguyen Jun 01 '20 at 08:48
  • @Thanh-QuyNguyen, you can check Node.js console output in CLI / logs to see the exact error that caused error 500. – Nikolai Kiselev Jun 01 '20 at 11:35