benhowdle89
benhowdle89

Reputation: 37464

Call an API function during the Nextjs build process (in `getStaticProps`) that hasn't been deployed yet

My project, deployed to Vercel

Nextjs site, with /pages/api/foo.ts

Inside /pages/index.tsx i make the following call:

const api = {
  async monthly(symbol) {
    const res = await fetch(`${server}/api/stocks?symbol=${symbol}`);
    const json = await res.json();
    return json;
  },
};

export async function getStaticProps() {
  const initial = await api.monthly(stock)
  return {
    props: {
      initial,
    },
    revalidate: 60,
  };
}

To get the server value in the above fetch call, i have this config file:

const dev = process.env.NODE_ENV !== "production";

export const server = dev
  ? "http://localhost:3000"
  : "https://fooproduction.com";

My exact question is: When I try to build (and deploy) this site, it can't do the static generation because the getStaticProps is calling an API function that doesn't yet exist in production (because NODE_ENV=production during build)

Am I doing something very wrong in the Vercel Nextjs™ way of building and deploying and calling API functions?

Upvotes: 3

Views: 892

Answers (1)

smootok
smootok

Reputation: 86

add a try catch inside getStaticProps and return empty props on error. your pages will be generated on runtime

Upvotes: 1

Related Questions