user3399180
user3399180

Reputation: 572

How to redirect using getStaticProps?

I have a nextjs application with simple user authentication. That means there are some protected routes that I don't want logged out user to get access to. The app compiles successfully in development build and works as expected. But when I use next build, I get an error saying -

Error occurred prerendering page "/createNewAdditionalInfo". Read more: https://err.sh/next.js/prerender-error

Error: 'redirect' can not be returned from getStaticProps during prerendering (/createNewAdditionalInfo).

Here's the code -

export async function getStaticProps(ctx) {
    let userObject;
    let id;
    const cookie = parseCookies(ctx);
    if (cookie.auth) {
        userObject = JSON.parse(cookie.auth);
        id = userObject.id;
    }
    if (!id) {
        return {
            redirect: {
                permanent: false,
                destination: '/',
            },
        };
    }

    return {
        props: {},
    };
}

Upvotes: 8

Views: 21845

Answers (3)

giraffesyo
giraffesyo

Reputation: 5342

From the asker's comments:

I need some way to redirect page from server side.

Next.js provides this, see the documentation.

You can achieve this by just switching the function getStaticProps to getServerSideProps. The entire function will execute on the server and your redirection will happen.

e.g.

export async function getServerSideProps() {
  return {
    redirect: {
      permanent: true,
      destination: 'https://giraffesyo.io',
    },
  }
}

Upvotes: -3

zvijude
zvijude

Reputation: 359

redirect from getStaticProps in nextJS

export async function getStaticProps({ params }) {
  const db = await getDB()

  //get id from url
  const id = params.postId

  //find post in db
  const post = await db().collection("posts").findOne({ _id: id })
  

  // The Redirect Happens HERE
  //if no post was found - go to Home page
  if (!post) {
    return {
      redirect: {
        destination: "/",
      },
    }
  }

  return {
    props: {
      post: JSON.stringify(post),
    },
  }
}


export async function getStaticPaths() {
  return {
    paths: [],
    fallback: true,
  }
}

Upvotes: 15

user3399180
user3399180

Reputation: 572

I was trying to run getStaticProps and getServerSideProps on firebase hosting. Firebase hosting only supports static site hosting. For anything backend related you have to use firebase functions.

I switched my hosting provider from firebase to vercel and everything works as it should be.

Upvotes: -8

Related Questions