⚙️Server

Setting up a custom server using Express.

Main Functions

There are several main functions of the code server are.

  • Disabling x-powered-by in response headers by next.js.

  • Access log in terminal server.

  • Development area on the server side.

  • Request listen for development console & production console.

Supporting Libraries

There are several supporting libraries to modify the server code

  • Express.js used to handle all development needs that run on the server side.

  • morgan used to handle HTTP request logger middleware for node.js.

  • chalk used to handle terminal string styling.

  • day.js used to handle parses, validates, manipulates, and displays dates and times for modern browsers with a largely Moment.js-compatible API on the server side.

Step 1: Installing Required Dependencies

The first step is to install the necessary dependencies for our logging monitor. In your project directory, run the following command:

yarn add express chalk morgan dayjs @types/express @types/morgan @types/chalk @types/dayjs

Step 2: Creating a Logger Utility

Create a new file called logger.ts in your src/server/logger folder. This file will contain a utility function to set up logging using Morgan and Chalk. Add the following code to logger.ts:

import chalk from 'chalk';
import dayjs from 'dayjs';
import morgan from 'morgan';

export const logger = morgan((tokens, req, res) => {
  const status = tokens.status(req, res);
  const method = tokens.method(req, res);
  const url = tokens.url(req, res);
  const responseTime = tokens['response-time'](req, res);
  const timestamp = dayjs().format('YYYY-MM-DD HH:mm:ss');

  const logLine = `[${timestamp}] ${chalk.green(
    method,
  )} ${url} ${status} ${chalk.blue(`${responseTime}ms`)}`;

  return logLine;
});

This utility function creates a Morgan logger instance and uses Chalk to colorize the output. It also includes the current timestamp using DayJS.

Step 3: Setting up Logging Middleware

Create a new file called loggingMiddleware.ts in your src/server/logger folder. This file will contain middleware to add our logger utility to Express. Add the following code to loggingMiddleware.ts:

import { logger } from './logger';

export const loggingMiddleware = (req, res, next) => {
  logger(req, res, next);
};

This middleware simply calls our logger utility function to log requests to the console.

Step 4: Adding Logging Middleware to Express

In your Next.js app, create a new file called server.ts in your project's root directory. This file will contain the code to set up Express and add our logging middleware. Add the following code to server.ts:

import express from 'express';
import { loggingMiddleware } from '@/server/logger/loggingMiddleware';

const app = express();

app.use(loggingMiddleware);

export default app;

This code sets up an Express app and adds our logging middleware to log all requests.

Step 5: Updating Your package.json file

Update your package.json file to use server.ts as the entry point for your application. In the "scripts" section, replace the "start" command with the following:

"start": "node ./node_modules/.bin/next start -p $PORT -H $HOST server.ts"

This command tells Next.js to use server.ts as the custom server for our app.

Step 6: Testing the Logging Monitor

Build your app for production using the following command:

yarn build

Then, start your app in production mode using the following command:

yarn start

Visit your app in the browser and navigate to a few pages. You should see log messages in your console that look something like this:

[2023-03-30 12:34:56] GET / 200 10.123ms
[2023-03-30 12:34:57] GET /about 200 5.678ms

These log messages include the timestamp, HTTP method, URL, response status, and response time for each request.

Last updated