DynamicServerError: Dynamic server usage: headers in NEXTJS 13.3

huangapple go评论75阅读模式
英文:

DynamicServerError: Dynamic server usage: headers in NEXTJS 13.3

问题

I'm Facing an issue while deployment of my Ecommerce Nextjs13 App on Vercel. Application works fine in local Environment but while hosting I got an error listed Below

Error in getting all categories: DynamicServerError: Dynamic server usage: headers
at staticGenerationBailout (/vercel/path0/.next/server/chunks/536.js:181:21)
at Object.headers (/vercel/path0/.next/server/chunks/616.js:201:62)
at handleReqBailout (/vercel/path0/.next/server/chunks/616.js:3048:35)
at Object.get (/vercel/path0/.next/server/chunks/616.js:3068:13)
at AuthCheck (/vercel/path0/.next/server/app/api/Admin/category/delete-category/route.js:237:23)
at GET (/vercel/path0/.next/server/app/api/Admin/category/getCategory/route.js:164:67)
at async /vercel/path0/.next/server/chunks/616.js:3352:37 {
digest: 'DYNAMIC_SERVER_USAGE'
}

Here's is What I am doing ,

I have a Dashboard Page, Where I fetch all categories' data and then set it in redux store, then in the child component, I get that data and display it in datatables

Here is my code

/api/Admin/category/getCategory

import connectDB from "@/DB/connectDB";
import AuthCheck from "@/middleware/AuthCheck";
import { NextResponse } from "next/server";
import Category from "@/model/Category";

export async function GET(req: Request) {
  try {
    await connectDB();
    const isAuthenticated = await AuthCheck(req);

    if (isAuthenticated) {
      const getData = await Category.find({});
      if (getData) {
        return NextResponse.json({ success: true, data: getData });
      } else {
        return NextResponse.json({ status: 204, success: false, message: 'No categories found.' });
      }
    } else {
      return NextResponse.json({ status: 401, success: false, message: "You are not authorized." });
    }
  } catch (error) {
    console.log('Error in getting all categories:', error);
    return NextResponse.json({ status: 500, success: false, message: 'Something went wrong. Please try again!' });
  }
}

Admin Dashboard Page

"use client"
import Cookies from 'js-cookie'
import { useRouter } from 'next/navigation'
import React, { useEffect } from 'react'
import AdminNavbar from '@/components/AdminNavbar';
import AdminSidebar from '@/components/AdminSidebar';
import SuperComponent from '@/components/SuperComponent';
import { ToastContainer, toast } from 'react-toastify';
import useSWR from 'swr'
import { get_all_categories } from '@/Services/Admin/category';
import { useDispatch } from 'react-redux';
import { setCatLoading, setCategoryData } from '@/utils/AdminSlice';


interface userData {
  email: String,
  role: String,
  _id: String,
  name: String
}

export default function Dashboard() {
  const Router = useRouter();
  const dispatch = useDispatch();

  useEffect(() => {
    const user: userData | null = JSON.parse(localStorage.getItem('user') || '{}');
    if (!Cookies.get('token') || user?.role !== 'admin') {
      Router.push('/')
    }
  }, [])

  const { data: categoryData, isLoading: categoryLoading } = useSWR('/gettingAllCategoriesFOrAdmin', get_all_categories)
  if (categoryData?.success !== true) toast.error(categoryData?.message)

  useEffect(() => {
    dispatch(setCategoryData(categoryData?.data))
    dispatch(setCatLoading(categoryLoading))
  }, [categoryData, dispatch, categoryLoading])

  return (
    <div className='w-full h-screen flex  bg-base-200 overflow-hidden'>
      <AdminSidebar />
      <div className='w-full h-full '>
        <AdminNavbar />
        <div className='w-full h-5/6  flex flex-wrap items-start justify-center overflow-y-auto  px-4 py-2'>
          <SuperComponent />
        </div>
      </div>
      <ToastContainer />
    </div>
  )
}
英文:

I'm Facing an issue while deployment of my Ecommerce Nextjs13 App on Vercel. Application works fine in local Environment but while hosting I got an error listed Below

Error in getting all categories: DynamicServerError: Dynamic server usage: headers
    at staticGenerationBailout (/vercel/path0/.next/server/chunks/536.js:181:21)
    at Object.headers (/vercel/path0/.next/server/chunks/616.js:201:62)
    at handleReqBailout (/vercel/path0/.next/server/chunks/616.js:3048:35)
    at Object.get (/vercel/path0/.next/server/chunks/616.js:3068:13)
    at AuthCheck (/vercel/path0/.next/server/app/api/Admin/category/delete-category/route.js:237:23)
    at GET (/vercel/path0/.next/server/app/api/Admin/category/getCategory/route.js:164:67)
    at async /vercel/path0/.next/server/chunks/616.js:3352:37 {
  digest: &#39;DYNAMIC_SERVER_USAGE&#39;
}

Here's is What I am doing ,

I have a Dashboard Page , Where I fetch all categories data and then set it in redux store , then In child component i get that data and display it in datatables

Here is my code

/api/Admin/category/getCategory

import connectDB from &quot;@/DB/connectDB&quot;;
import AuthCheck from &quot;@/middleware/AuthCheck&quot;;
import { NextResponse } from &quot;next/server&quot;;
import Category from &quot;@/model/Category&quot;;

export async function GET(req: Request) {
  try {
    await connectDB();
    const isAuthenticated = await AuthCheck(req);

    if (isAuthenticated) {
      const getData = await Category.find({});
      if (getData) {
        return NextResponse.json({success  :true , data : getData});
      } else {
        return NextResponse.json({status: 204 , success: false, message: &#39;No categories found.&#39; });
      }
    } else {
      return NextResponse.json({status: 401 , success: false, message: &quot;You are not authorized.&quot; });
    }
  } catch (error) {
    console.log(&#39;Error in getting all categories:&#39;, error);
    return NextResponse.json({status : 500 , success: false, message: &#39;Something went wrong. Please try again!&#39; });
  }
}

Admin Dashboard Page

&quot;use client&quot;
import Cookies from &#39;js-cookie&#39;
import { useRouter } from &#39;next/navigation&#39;
import React, { useEffect } from &#39;react&#39;
import AdminNavbar from &#39;@/components/AdminNavbar&#39;;
import AdminSidebar from &#39;@/components/AdminSidebar&#39;;
import SuperComponent from &#39;@/components/SuperComponent&#39;;
import { ToastContainer, toast } from &#39;react-toastify&#39;;
import useSWR from &#39;swr&#39;
import { get_all_categories } from &#39;@/Services/Admin/category&#39;;
import { useDispatch } from &#39;react-redux&#39;;
import { setCatLoading, setCategoryData } from &#39;@/utils/AdminSlice&#39;;


interface userData {
  email: String,
  role: String,
  _id: String,
  name: String
}



export default function Dashboard() {
  const Router = useRouter();
  const dispatch  = useDispatch();
  
  useEffect(() =&gt; {
    const user: userData | null = JSON.parse(localStorage.getItem(&#39;user&#39;) || &#39;{}&#39;);
    if (!Cookies.get(&#39;token&#39;) || user?.role !== &#39;admin&#39;) {
      Router.push(&#39;/&#39;)
    }
  }, [])



  const { data : categoryData , isLoading : categoryLoading } = useSWR(&#39;/gettingAllCategoriesFOrAdmin&#39;, get_all_categories)
  if (categoryData?.success  !== true) toast.error(categoryData?.message)

  useEffect(() =&gt; {
   dispatch(setCategoryData(categoryData?.data))
    dispatch(setCatLoading(categoryLoading))

  }, [categoryData , dispatch , categoryLoading])
 


  return (
    &lt;div className=&#39;w-full h-screen flex  bg-base-200 overflow-hidden&#39;&gt;
      &lt;AdminSidebar /&gt;
      &lt;div className=&#39;w-full h-full &#39;&gt;
        &lt;AdminNavbar /&gt;
        &lt;div className=&#39;w-full h-5/6  flex flex-wrap items-start justify-center overflow-y-auto  px-4 py-2&#39;&gt;
         &lt;SuperComponent /&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;ToastContainer /&gt;
    &lt;/div&gt;
  )
}





答案1

得分: 5

我通过在我的API路由文件中添加export const dynamic = 'force-dynamic';来修复了这个错误。

英文:

I fixed this error by adding

export const dynamic = 'force-dynamic' in my Api routes file
DynamicServerError: Dynamic server usage: headers in NEXTJS 13.3

huangapple
  • 本文由 发表于 2023年5月7日 09:27:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76191857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定