gidgud
gidgud

Reputation: 251

How to handle error response in Next.js 13 Server Component?

So I'm trying to fetch data that needs token header for authorization in Server Component page.tsx. The data itself comes from external backend/API and it can response with different status code. If Unauthorized it will response with status 401, if Not Found it will response with status 404. Here I already provided a handle for each different error status:

const getItems = async (): Promise<IGetItemsResponse> => {
  const res = await fetch(`${process.env.API_URL}items`, {
    headers: {
      Authorization: `Bearer ${cookies().get('access_token')?.value}`,
    },
  });

  if (res.status === 404) {
    notFound()
  }
  if (res.status === 401) {
    const response = NextResponse.next();
    response.cookies.delete('access_token');
    response.cookies.delete('expiry_token');
    return response;
  }
  if (!res.ok) {
    throw new Error('Something went wrong!');
  }
  return res.json();
};

export default async function Page() {
  const items = await getItems()
  return <ItemList initialData={items}/>;
}

When it response with 404 Next.js succeed showing the nearest not-found.tsx. However the problem here is the 401 error, I don't know why Next.js won't delete the cookie as I already handle the 401 error response there. Instead deleting the cookie, Next.js just run the throw new Error('Something went wrong!'); right away which lead to showing the nearest error.tsx. And then in error.tsx component, it shows the right error message in development build, but in production build it shows this different error message: error message in production build

Been searching and debugging for hours, yet still don't know why it won't handle the error. Please is there any way to properly handle this different error status in Next.js 13 Server Component? I need to at least delete the token cookies if it responses 401.

Thanks.

Upvotes: 5

Views: 1670

Answers (1)

Philipe Almeida
Philipe Almeida

Reputation: 41

If you are using Next.js with the new App Router version (13.4 or newer), the next.js documentation recommend the use of the package next/headers for the cookie manipulations on server side like below.

Use NextResponse statement after the cookie delete.

import { cookies } from 'next/headers'

async function yourFn() {
  cookies().delete('cookie-name')
}

Upvotes: 0

Related Questions