javascriptreactjsroutesnext.jsapp-router

Next js 13 App router build error. (when i try fetch api route in server component)


I get an error when i build next app (yarn run build)

I made new clean project i tried there. This is my route (/api/categories/route.ts)

export async function GET() {
  return new Response(JSON.stringify({ msg: "categories" }));
}

And my /page.tsx:

export default async function Home() {
  const res = await fetch("http://localhost:3000/api/categories");
  console.log(await res.json());

  return (
    <main>
      <h1>Home</h1>
    </main>
  );
}

When i run dev app (yarn run dev) i dont have any errors but when i try build i get this error:

error

I tried also fetch data from fake data json api that i found in web and it worked perfect. But when i try to use my api routes i have an error.

And i tried to change url like: /api/categories and http://127.0.0.1/api/categories

Is there any way I can solve this problem? Because i want to deploy my app.

But when i use prisma in project and i tried to fetch data from prisma exact in page.tsx like: prisma.categories.findMany(...), i dont have problem. But i want thet code will be clean, i have many options for findMay(). So maybe you know how i can solve this without using prisma right in page.tsx


Solution

  • You can’t use local api routes to fetch data in server components because api routes are not available at build time. Unfortunately, it’s a limitation in current version of Next.is that I hope will be addressed in future versions.