A Better Way to Debug Server-Side Code
Logs are a very common way to debug server code. Full stack developers typically have to check both client side and server side logs. Find out how to get both server and client side logs in the browser.
Table of Contents 📖
ConsoleLog
My chrome extension ConsoleLog can now be used to view server logs in the browser. This is great because we can have all our server side and client side logs in the same place.
Server Setup
To do this, we need to set specific headers on the response. If you are using Express, this is easily done with a middleware I created called @wittcode/console-log-middleware.
npm i @wittcode/console-log-middleware
After installing the package, import it and add it as global middleware. We also have to pass an options object to enable it. When enabled, any console.log, console.error, etc. will be logged to the browser in a friendly and configurable popup.
import express from 'express';
import consoleLogMiddleware from '@wittcode/console-log-middleware';
const app = express();
app.use(consoleLogMiddleware(({
enabled: process.env.NODE_ENV === 'development',
logToConsole: true
})));
app.get('/', (req, res) => {
console.log(`${req.method} ${req.url}`);
console.error('user not found', {user: 'WittCode', extension: 'ConsoleLog'})
return res.send('Hello World how are you doing??');
});
app.listen(3500, () => {
console.log('Example app listening on port 3500!');
});
SUCCESS: The logToConsole property makes the middleware log to the console as well as the browser.
This middleware is a very small package so it should have no impact on bundle sizes. However, it should only really be enabled in development. This means that we can set the enabled flag by checking the NODE_ENV environment variable.