nextjs 13 generateStaticParams与next/header一起使用导致开发模式下未处理的运行时错误

yr9zkbsy  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(302)

我正在做一个新的项目,最近在我的前端应用程序中使用了nextjs 13。
当将函数generateStaticParams与next/header库函数headers()一起使用时,
我在dev模式下得到一个错误。
未处理的运行时错误-动态服务器使用情况:标题
Screenshot of Error occured during dev mode
但是当前端使用next build / next start时,错误不会出现。
我使用next/header库的主要原因是由于next-auth,以获得对cookie的访问。
generateStaticParamsapp/detail/[questionId]/page.tsx文件中next/heads在app/layout.tsx文件中

app/page.tsx

import React from "react";
import QuestionCard from "../components/Card/QuestionCard";
import Carousel from "../components/Carousel/Carousel";
import HomeNavBar from "../components/HomeNavBar/HomeNavBar";
import { ICarousel } from "../types/carousel";
import TabNavigator from "../components/TabNavigator/TabNavigator";

const getGoogleSession = async () => {};

const getQuestionList = async () => {
  const response = await fetch(`https://pioneroroom.com/questionlist`);
  const data = await response.json();
  return data;
};

const page = async ({ Question }: any) => {
  // const imageArr = await getCarouselImages();
  const data = await getQuestionList();

  return (
    <div className="main">
      <HomeNavBar />
      {/* <Carousel carousel={imageArr} /> */}
      <div className="contentbody">
        {data.data.map((e: any) => {
          return <QuestionCard key={e.questionId} question={e} />;
        })}
      </div>

      <TabNavigator activeLink={""} />
    </div>
  );
};

export default page;

app/layout.tsx

import { Roboto, Noto_Sans_KR } from '@next/font/google';
import NavBar from '../components/HomeNavBar/HomeNavBar';
import '../styles/globals.css';

import SessionContainer from '../components/Providers/SessionProvider';
import '../styles/globals.css';
import { unstable_getServerSession } from 'next-auth';
import { getSession } from '../utils/helper/session';
import { cookies, headers } from 'next/headers';
import HomeNavBar from '../components/HomeNavBar/HomeNavBar';
import TabNavigator from '../components/TabNavigator/TabNavigator';

const noto = Noto_Sans_KR({
    weight: '400',
    fallback: ['Roboto'],
    subsets: ['latin'],
});

const RootLayout = async ({ children }: any) => {
    const { segment } = children.props.childProp;
    const session = await getSession(headers().get('cookie') ?? '');
    const nextCookies = cookies();
    return (
        <html className={noto.className}>
            <head>
                <meta name="viewport" content="width=device-width,initial-scale=1" />
                <title>asdf</title>
            </head>
            <body>
                <SessionContainer session={session}>{children}</SessionContainer>
            </body>
        </html>
    );
};

export default RootLayout;

app/detail/[questionId]/page.tsx

import { headers } from 'next/headers';
import React, { use } from 'react';
import { getSession } from '../../../utils/helper/session';

const fetchPost = async (id: any) => {
    const res = await fetch(`https://pioneroroom.com/questionlist/${id}`);
    return await res.json().then((res) => res.data);
};

const DetailIdPage = async ({ params }: any) => {
    console.log('params.questionId', params.questionId);
    const post = await fetchPost(params.questionId);
    return (
        <div>
            <p>{JSON.stringify(post)}</p>
        </div>
    );
};

// BUG: generateStaticParams 함수가 현재 dev 모드에서 동작하지 않음.
// dynamic headers( next/headers )의 cookie등을 불러올 때 오류를 일으키고,
// dev mode에서 이 함수와 결합하여 사용하면 dynamic server usage: headers error 발생함.
/*
export async function generateStaticParams() {
    const res = await fetch('https://pioneroroom.com/questionlist');
    const data = await res.json();
    const arr = data.data.map((e: any) => {
        console.log('map', e.questionId);
        return {
            questionId: String(e.questionId),
        };
    });
    return arr;
}
*/

export default DetailIdPage;

删除两个代码(generateStaticParams or next/header)中的任何一个都可以解决这个问题。在开发模式下未发生错误。

8xiog9wr

8xiog9wr1#

我用来阻止这些错误发生的解决方法是在开发模式下完全关闭静态渲染。(但保持在prod)
在导出generateStaticParams()的文件中添加以下内容:

// what used to be export function generateStaticParams
function staticParams(){
...
}

// fix "dynamic server usage" errors in dev mode by turning off static generation and forcing dynamic rendering
export const generateStaticParams =  process.env.NODE_ENV === "production" ? staticParams :  undefined;
export const dynamic =  process.env.NODE_ENV === "production" ? 'auto' : 'force-dynamic';

相关问题