【问题标题】:How to redirect using getStaticProps?如何使用 getStaticProps 进行重定向?
【发布时间】:2021-04-18 21:43:56
【问题描述】:

我有一个带有简单用户身份验证的 nextjs 应用程序。这意味着有一些受保护的路由我不希望注销的用户访问。该应用程序在开发版本中成功编译并按预期工作。但是当我使用next build 时,我收到一条错误消息 -

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).

这是代码 -

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: {},
    };
}

【问题讨论】:

  • Error: 'redirect' can not be returned from getStaticProps during prerendering 这里有什么不明白的?附言。你在 React 中,你可以使用 useEffect 钩子来检查重定向吗? :) 更好的答案在这里:github.com/vercel/next.js/discussions/14890
  • 由于getStaticProps 在构建时执行,这是不可能的。作为@MiloshN。提到,您可以在组件中使用 useEffect 进行客户端重定向。
  • 用户可以在被重定向之前访问该页面几秒钟。由于 useEffect 在初始渲染之后运行,而不是之前。我需要一些方法来从服务器端重定向页面。

标签: reactjs routes next.js


【解决方案1】:

从 nextJS 中的 getStaticProps 重定向

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,
  }
}

【讨论】:

    【解决方案2】:

    您只需将函数getStaticProps 切换为getServerSideProps 即可实现此目的。整个函数将在服务器上执行,您的重定向将发生。

    例如

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

    【讨论】:

      【解决方案3】:

      我试图在 firebase 主机上运行 getStaticPropsgetServerSideProps。 Firebase 托管仅支持静态站点托管。对于任何与后端相关的内容,您都必须使用 firebase 函数。

      我将托管服务提供商从 firebase 切换到 vercel,一切正常。

      【讨论】:

        猜你喜欢
        • 2013-04-18
        • 1970-01-01
        • 1970-01-01
        • 2020-06-03
        • 2023-03-05
        • 2020-09-20
        • 1970-01-01
        • 1970-01-01
        • 2019-10-09
        相关资源
        最近更新 更多