GianGonzaga29
12/20/2018 - 8:27 AM

How to Create Middleware

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.

const express = require('express');

const app = express();

app.use((req, res, next) => {
    // This will run when the client makes a request to the page
    req.name = 'Gian' // Will be made available throughout the whole app
    console.log('Hey Retard!');
    next();
})

app.get('/', (req, res) => {
  res.send(req.name)
})

app.listen(3000)