DEV Community

loading...

NodeJS: How To Add Additional Middleware To Our Express Server

miku86 profile image miku86 Updated on ・2 min read

Intro

So we installed NodeJS on our machine.

We also learned how to create a simple server using express.

Now we want to learn how to add additional middleware to our express server.

Reuse our simple server from the last article

  • Open your terminal
  • Create a file named index.js:
touch index.js
Enter fullscreen mode Exit fullscreen mode
  • Add this JavaScript code into it:
const express = require('express');
const app = express();

const PORT = 8080;

app.get('/', (request, response) => {
  response.send('Hello World');
});

app.listen(PORT, () => {
  console.log(`Server running at: http://localhost:${PORT}/`);
});
Enter fullscreen mode Exit fullscreen mode

Note: This is our starting point, we have one working route.
I updated req to request & res to response to increase readability.


Additional Middleware

What is Middleware?

Sometimes you want to add additional functionality between the default request-response-cycle. Let's say you want to get some detailed information about the current request.

You can write a simple middleware, that handles this task, and add it to your express app.

Create a Middleware

  • Create a file named logger.js:
touch logger.js
Enter fullscreen mode Exit fullscreen mode
  • Add this JavaScript code into it:
const logger = (req, res, next) => {
  console.log(`Time: ${new Date()} - Method: ${req.method} - Path: ${req.originalUrl}`);
  next();
};

module.exports = logger;
Enter fullscreen mode Exit fullscreen mode
  • Require the new logger in index.js and use the middleware:
// import express (after npm install express)
const express = require('express');

// import the logger
const logger = require('./logger');

// create new express app and save it as app
const app = express();

// server configuration
const PORT = 8080;

// use the middleware
app.use(logger);

// create a route for the app
app.get('/', (req, res) => {
  res.send('Hello World');
});

// make the server listen to requests
app.listen(PORT, () => {
  console.log(`Server running at: http://localhost:${PORT}/`);
});
Enter fullscreen mode Exit fullscreen mode

Run it from the terminal

  • Run it:
node index.js
Enter fullscreen mode Exit fullscreen mode
Server running at: http://localhost:8080/
Time: Tue Sep 03 2019 17:32:30 GMT+0200 (Central European Summer Time) - Method: GET - Path: /
Enter fullscreen mode Exit fullscreen mode

Series on Express and PostgreSQL

Here you can find my series about Express and PostgreSQL


Further Reading


Questions

  • What's your favorite middleware for express?

Discussion (0)

pic
Editor guide