Skip to content

Conversation

@kikoruiz
Copy link
Member

@kikoruiz kikoruiz commented Nov 26, 2025

Add error handling and logging support to server-side getInitialProps

Changes

  • Wrap server-side getInitialProps execution in try-catch block to prevent application crashes
  • Add optional logger parameter to loadPage function for error reporting
  • Return an object containing the error message instead of propagating an exception
  • Define Logger type with error method signature

🚨 BREAKING CHANGES

  • Removed first positional contextFactory param

Motivation

When getInitialProps throws an error on the server, it can crash the entire SSR process. This change adds resilience by catching errors and optionally logging them for observability.

Usage

import loadPage from '@s-ui/react-initial-props/lib/loadPage'

const myLogger = {
  error: (message, error) => {
    console.error(message, error)
    // Send to your logging service
  }
}

const loader = loadPage(() => import('./MyPage'), myLogger)


logger?.error?.(message, error as Error)

return {error: error instanceof Error ? error.message : message}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not just throw an error so we do not change the previous behavior?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, maybe it's better to log the error and then throw it instead of returning a new object, I'm doing some tests locally before

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants