尝试从 getStaticProps 重定向在构建期间返回错误

时间:2021-03-31 10:30:27

标签: next.js

我目前正在尝试根据检查 cookie 的 API 调用在 getStaticProps 内部重定向。如果 cookie 存在,则用户通过身份验证,这意味着没有重定向,但如果缺少,则重定向。

import React from "react";
import { GetStaticProps } from "next";

const Chat: React.FC = () => {
    return null;
};

export const getStaticProps: GetStaticProps = async ({ locale, defaultLocale }) => {
    const { authenticated } = await fetch("http://localhost:4000/api/auth").then(res => res.json());

    if (!authenticated) {
        return {
            redirect: {
                permanent: false,
                destination: "/user/login",
            },
        };
    }

    return {
        props: {
            defaultLocale,
            locale,
        },
    };
};

export default Chat;

这在运行时工作正常,但在构建时,我收到以下错误:

<块引用>

错误:在预渲染 (/chat) 期间无法从 getStaticProps 返回 redirect

怎么会? The official next.js doc even shows how to redirect from getStaticProps. I even added the redirect to next.config.js,但不知何故它仍然失败。

module.exports = {
    async redirects() {
        return [
            {
                source: "/chat", 
                destination: "/user/login",
                permanent: false,
            },
        ];
    },
    ...
}

仅供参考,该应用程序使用 i18n 来处理翻译、语言环境等。

0 个答案:

没有答案