Matt
Matt

Reputation: 35203

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

Upvotes: 3

Views: 7189

Answers (4)

Alexandr Zabirov
Alexandr Zabirov

Reputation: 1

To use redirects you can use the redirects key in next.config.js:

next.config.js

module.exports = {
  async redirects() {
    return [
      {
        source: '/about',
        destination: '/',
        permanent: true,
      },
    ]
  },
}

Upvotes: 0

Daivagna Nanavati
Daivagna Nanavati

Reputation: 111

Initially i was also confused as i had the same issue where even if redirect syntax are allowed in getStaticProps, still then you give redirect items into GetStaticProps, it comes up with above exception

Actual issue is "Redirects are possible in GetStaticProps, but they are not possible during build and prerendering time" and that is why it is complaining that "it is not possible"

So just before GetStaticProps, GetStaticPaths is called, and it internally calls "sitemap-fetcher", in that you will need to customize the DefaultSitemap query so that it ignores those pages with redirect templates

What it will do is, it will ignore those pages from the array of pages which are fed to "GetStatiProps" and once you exclude those pages from being prerendered

you when you build and if those paths are excluded using your custom graphQL query, it will not complain about it

Let me know if you need detail code, i have it handy and can give it to you

Upvotes: 1

Dupflo
Dupflo

Reputation: 396

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

Upvotes: 3

Matt
Matt

Reputation: 35203

It is not currently possible to redirect from the server with Next.js static pages.

I hope they can make it happen some day, but until then the workaround is to load the page and then redirect client-side using the useEffect react hook.

import React, { useEffect } from "react";
import { useRouter } from "next/router";

const IndexPage = ({ data }) => {
  const router = useRouter();
  useEffect(() => {
    if (data?.home?.isRedirect) {
      router.push(data.home.redirectTo);
    }
  });
  return (
    <>
      {data && !data.isRedirect && (
      ...

Notice how I check for !data.isRedirect? This is to prevent the screen from flashing before the redirect.

Upvotes: 5

Related Questions