Express.js Routing and Middleware

The imported express library returns a function that, when invoked, creates the Express application object (app). This object configures the server and define its routes.

const express = require('express');
const app = express();

A middleware is an express function called during route requests, it has access to the request and response objects, its next() function passes control to the next stack/route handler.

//It can be included directly in the Route request
function steps(req, res, next){
  console.log("first step")
  next()
}

app.get("/first", steps ,(req, res)=>{
  res.send("end stack")  //first step, end stack
})

The express method app.use() mounts the middlewares on the route paths.

If no route is specified then it's applied to every route, their order depends on when were they declared.

//Aplied to all requests routes
app.use(steps)

app.get("/ruota", (req, res)=>{
  console.log("This is the return")  //first step, this is the return
  res.send("how does a middleware work")
})

//This middleware will be ignored.
app.use("/ruota", (req, res, next)=>{
  console.log("This is the second")

  next()
})

A middleware can end a route path with res.send() and res.redirect().

Middlewares can update req.body and pass error parameters to the route handler.

chevron-rightError handling middleware with next(err)hashtag

The middleware error handler requires 4 parameters, and will inherit the error object.

This is useful to handle errors before they reach the route handler function.

We can module.export middlewares to use() in the router.

Independent routing with express.router()

The express.router() class create independent routing instances, which need to be mounted to a specific path using app.use(), effectively prefixing all routes defined within the router.

it inherits methods and properties from the express framework (like middlewares).

We implement route chaining using the router.route() method.

Password hashing with bycryptjs

The bcrypt module is a wrapper library for the C-based bcrypt password hashing algorithm. It provides a javascript API to hash passwords, due to the C compilation, extra dependencies may be required depending on the platform.

The npm i bcryptjs module is a pure JavaScript implementation of the bcrypt algorithm, it doesn't require external code and runs directly in Node.js.

Its getSalt(rounds) method generates a random string used for the hash() of the password.

Bcryptjs provides synchronous versions of its promise-based methods, which block the execution of the program until they complete and return a value.

The compare() method compares a plaintext and a hashed password, using its salt, to return a boolean value.

The getRounds() method extracts the number of rounds used in the salt process.

We manage its error handling with a try/catch block:

Last updated