Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: `redirect` can not be returned from getStaticProps during prerendering

In my Next.js application I am statically generating pages using getStaticProps like so

export async function getStaticProps({ params }) {
  
  ...

  if (data.isRedirect) {
    return {
      redirect: {
        destination: `${data.redirectTo}`,
        permanent: false,
      },
    };
  }
  return {
    props: {
      data,
    },
    revalidate: 10,
  };
}

It is working just as expected on localhost but when I deploy to Vercel i get this error.

Error: redirect can not be returned from getStaticProps during prerendering

I don't understand this as Next.js has this example in their docs. https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation

like image 415
Matt Avatar asked May 21 '26 23:05

Matt


1 Answers

I found a workaround

I am using getStaticProps and also using dynamic revalidation but also using fallback: 'blocking' to manage my path which mean that my app will look at my headless CMS api to fetch non existant path/page at build time.

Since I am doing a check based on process.env.npm_lifecycle_event who can tell if you are building or running your app

if (process.env.npm_lifecycle_event === 'build')
  return {
    notFound: true
  }
return {
  redirect: {
    destination: '/404',
    permanent: false,
  },
}

Then if I am building my app I am returning notFound: true. Once I am running it will prefetch the path and then return my page to a my 404. I don't want it to be permanent since I am using dynamic revalidation.

With this check I can then avoid the following error

Error: redirect can not be returned from getStaticProps during prerendering

like image 190
Dupflo Avatar answered May 24 '26 16:05

Dupflo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!