Skip to content

Instantly share code, notes, and snippets.

@amitsingh-007
Last active December 5, 2022 14:48
Show Gist options
  • Save amitsingh-007/2576029ca785314019069ab49aa8f7ef to your computer and use it in GitHub Desktop.
Save amitsingh-007/2576029ca785314019069ab49aa8f7ef to your computer and use it in GitHub Desktop.
Monkey patch console.error() to process React hydration errors
//Update this array to catch more errors
const HYDRATION_ERROR_MSGS = [
"Warning: Did not expect server HTML to contain",
"Warning: Text content did not match. Server",
];
//Can use any npm packag instead of this
const interpolate = (template, params) =>
params.reduce((p, c) => p.replace(/%s/, c), template);
const isReactHydrationError = args => {
const errorArg = args && args[0];
return (
errorArg &&
typeof errorArg.includes === "function" &&
HYDRATION_ERROR_MSGS.some(msg => errorArg.includes(msg))
);
};
const logHydrationError = args => {
args[0] = `ReactHydrationError - ${args[0]}`;
const [template, ...params] = args;
const error = interpolate(template, params);
//Function to log this error in the desired error logging channel
reportError({ error });
};
const patchConsoleError = () => {
//Save reference to original error() function
const { error } = console;
console.error = function () {
if (isReactHydrationError(arguments)) {
logHydrationError(arguments);
}
error.apply(console, arguments);
};
};
export default patchConsoleError;
@horatiorosa
Copy link

I am new to React and would love to make use of this gist, but I don't know how to use it. Would you be able to post or describe an example of how to use it?

@amitsingh-007
Copy link
Author

@horatiorosa Hey, I am a bit late on your comment. I will post its working usage if you let me know if you still need it, otherwise, I will assume you found some way to make it work.

@horatiorosa
Copy link

Yes, please post the working usage. This hydration error is driving me mad! :-p

@amitsingh-007
Copy link
Author

Hey, I have added a demo here: https://github.com/amitsingh-007/react-hydration-error and also hosted it(which is meaningless since we can only catch it in dev env). I have added all the steps on how to run this on your local machine. Let me know if you still are having some trouble with it. Peace

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