Sometimes developers on my team work with their console / dev tools window closed, and therefore miss key Next.js or React Js error and warning messages in the console.
I've tried overriding console.error and console.warn to prepend text into our app, only when the URL includes 'localhost', in hopes that I could draw attention to these errors, but it's not working reliably.
export default function App() {
useEffect(() => {
if (typeof window !== 'undefined') {
const url = window.location.href;
if (url.match(/localhost/i)) {
// define a new console
function buildDevConsole(oldCons) {
return {
log: function(text){
oldCons.log(text);
// Your code
},
info: function (text) {
oldCons.info(text);
// Your code
},
warn: function (text) {
oldCons.warn(text);
const pre = document.createElement("pre");
pre.textContent = text;
document.body.prepend(pre);
},
error: function (text) {
oldCons.error(text);
const pre = document.createElement("pre");
pre.textContent = text;
document.body.prepend(pre);
}
};
}
window.console = buildDevConsole(window.console);
}
}
}, []);
// ... rest of function omitted
Is anyone aware of a way to know that errors or warnings are occuring with the console closed, during localhost next dev
development?
EDIT (19-Oct-2022)
One workaround is to let a chrome extension help with this. I've asked our team to install a plugin such as "Chrome JS Error Icon", which is one of many choices for things that proactively tell you that you should open your console. This extension can be restricted to localhost only in the extension settings.
I still would love a solution that works for modern browsers to somehow inject these into the page, but it's proving to be less reliable than I had hoped, for unknown reasons. (specifically, warnings will come into the page after a hard refresh, but not errors, with my implementation shown above).