2

I am using Next.js with the Vercel deployment workflow, I am following this guide to try and setup page generation at buildtime. The specific section shows the following example to generate pages based on an external API's response:


// This function gets called at build time
export async function getStaticPaths() {
  // Call an external API endpoint to get posts
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // Get the paths we want to pre-render based on posts
  const paths = posts.map(post => ({
    params: { id: post.id },
  }))

  // We'll pre-render only these paths at build time.
  // { fallback: false } means other routes should 404.
  return { paths, fallback: false }
}

// This also gets called at build time
export async function getStaticProps({ params }) {
  // params contains the post `id`.
  // If the route is like /posts/1, then params.id is 1
  const res = await fetch(`https://.../posts/${params.id}`)
  const post = await res.json()

  // Pass post data to the page via props
  return { props: { post } }
}

I want to do this exactly, however I wrote my API as a Node.js serverless function within the same code repository, it is not an external api.

I tried to do the following to call on my api:

// This function gets called at build time
export async function getStaticPaths() {
    const res = await fetch('/api/get-designs');
    const designs = await res.json();

    // Get the paths we want to pre-render based on posts
    const paths = designs.map(design => ({
        params: { id: design.id },
    }))

    return {
        // Only posts returned by api are generated at build time
        paths: paths,
        // Enable statically generating additional pages
        fallback: true,
    }
}

However I get an error that the fetch api url must be absolute. Because of the way Vercel deploys, I won't always have the same deployment URL, so I don't think I can just use a hardcoded value here. Also, I am suspecting that because this function runs at buildtime, that my function is not running yet, therefore can not be called. I am still trying to wrap my head around this Next.js statically generated site workflow, but basically I am confused because they seem to encourage using serverless functions, and this getStaticPaths method for page generation, but they don't seem to work together unless I am missing something.

Is there a way I can run my api to get these results at build time? Any guidance would be much appreciated! Thanks!

Lara
  • 516
  • 1
  • 3
  • 9

1 Answers1

0

In this case, we can extract the server logic into a function and that function can be used directly inside your api route file. So, for CR we can use /api/whateverRoute and inside getStaticPaths we can use that function itself directly.

lokprakash
  • 420
  • 3
  • 9