Search code examples
next.jsstatic-generatorincremental-static-regeneration

Incremental Static Regeneration Nextjs 13 without API call


I want to be able to use Incremental static regeneration when calling an endpoint in my Nexjs 13 app. The problem is that my endpoint is an Edge function so I get the following error when building my code:

enter image description here

This error is displayed when I try to call my Edge function like this in the app/ directory.

async function fetchPosts() {
  const res = await fetch(`${basePath}/api/myExpensiveEndpoint`, { next: { revalidate: 60 } });
  const data = await res.json();

  return data.posts;
}

I think this is expected because its a Nextjs Edge function and they are not allow to be called in Static Generation methods. The solution should be calling the method directly instead of the API. Something like this:

import { myExpensiveFunction } from '../../lib/functions'

export async function getStaticProps() {
  const data = await myExpensiveFunction()

  return {
    props: { posts: data.posts },
    revalidate: 60,
  };
}

But Nexjs13 does not support getStaticProps in the new app/ directory so that would not work. So I was trying to look for a work around this without using the old pages/ directory.


Solution

  • import { fetchExpensiveCalculation } from '../../lib/expensiveCalculation'
    
    export const revalidate = 3600;
    
    async function ExampleComponent () {
      const schedule = await fetchExpensiveCalculation()
    }
    

    Calling my function and exporting the constant revalidate did the trick :)

    Here is the source: https://beta.nextjs.org/docs/data-fetching/fetching#segment-cache-configuration