0

Given a Server Component (or Server Action) that fetches data, how can I access the full error message for server-side logging purposes?

Example:

import os from 'os';
import { PHASE_PRODUCTION_BUILD } from 'next/constants';

export const dynamic = 'force-dynamic'

async function getDataFromServer(): Promise<string> {
  if (process.env.NEXT_PHASE !== PHASE_PRODUCTION_BUILD) {
    throw new Error('Error from server');
  }

  return Promise.resolve(`OS Type: ${os.type()}`);
}

export default async function Home() {
  const serverData = await getDataFromServer();

  return (
    <p>From server: {serverData}</p>
  )
}

Running this in a "production" version (npm run build, npm run start) results in

An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.

I do not want to expose the actual error message to clients, but I want to log it to a service server-side. Error boundaries are client-side, so they get the sanitized message.

The only way I've found is to wrap every server method in try..catch. I can create a higher-order function to reduce the boilerplate, but is there a way to create a single server-side error handler (without delegating from every catch block)?

1 Answer 1

0

In order to access the full error message for server-side logging purposes in a Next.js Server Component or Server Action, you can use a try catch.

import os from 'os';
import { PHASE_PRODUCTION_BUILD } from 'next/constants';

export const dynamic = 'force-dynamic'

async function getDataFromServer(): Promise<string> {
  if (process.env.NEXT_PHASE !== PHASE_PRODUCTION_BUILD) {
    throw new Error('Error from server');
  }

  return Promise.resolve(`OS Type: ${os.type()}`);
}

export default async function Home() {
  let serverData;
  try {
    serverData = await getDataFromServer();
  } catch (error) {
    // Log the full error message server-side
    console.error('Server error:', error);

    // You can choose to return a fallback value or rethrow the error if needed
    serverData = 'Error fetching data';
  }

  return (
    <p>From server: {serverData}</p>
  );
}
Sign up to request clarification or add additional context in comments.

2 Comments

Right, but I want to do this in one place for all pages / server components. Wrapping every component in a try..catch is messy and error-prone.
in order to get all component errors for individual component I think it will be not possible as we need something in order to check for error for the particular component/function like an event

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.