How to properly handle server-side errors in Next.js 14?

1.2k views Asked by At

I'm working on a Next.js 14 project, and I have a setup where I make API requests using fetch in a handler.tsx file like this:

async function getPositions() {
  const response = await fetch(
    process.env.BASE_API_URL + "/positions?enabled=true",
    {
      cache: "no-cache",
    }
  );

  if (!response.ok) {
    throw new Error("Es gab ein Problem mit Ihrer Anfrage");
  }

  const data = await response.json();
  return data.result;
}

export { getPositions };

In my page file page.tsx I simply call the getPositions function and assume that any server-side errors will be caught in a global error handler:

import { getPositions } from "./handler";

export default async function Page() {
  const positions = await getPositions();

  console.log(positions);

  return (
    <>
      <h1>Positions</h1>
    </>
  );
}

According to the Next.js documentation, it seems like I don't have to catch the error explicitly and can let it propagate through to be caught in a separate error handler error.tsx. Is this approach correct and are there any best practices for handling server-side errors in Next.js 14?

2

There are 2 answers

3
Bob On BEST ANSWER

This is perfectly fine approach

However you can add your error.jsx closer to your page to prevent disabling full ui to your users

0
Varun On

you can also try this in Next 14 , APP router , server side

return NextResponse.json({message:Internal Server error, status:500})