NodeJS: Mixed topics


Chained Middleware

The following example shows how we can chain multiple (in this case two) middlewares.

The first middleware is a logger function, which writes ‘Request arrived’ in the terminal window where the NodeJS web app (app.js) was started.

The second middleware is a time function, which stored the request time in a property.

The two middleware are chained with app.use().

The first middleware calls the second middleware with next() and so does the second middleware call the route function.

app.js

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

const loggerMiddleware = function (req, res, next) {
  console.log('Request arrived')
  next()
}

const timeMiddleware = function (req, res, next) {
  req.requestTime = Date.now()
  next()
}

app.use(loggerMiddleware)
app.use(timeMiddleware)

app.get('/', (req, res) => {
  let response = 'Hello World!<br>'
  response += `<small>Request time was: ${req.requestTime}</small>`
  res.send(response)
})

app.listen(3000)

As soon as the browser sends a request that matches the route the log text in terminal and the time string on the web side are written:

Troubleshooting

Type error: Property ‘session’ does not exist on type ‘{}’

Problem

You try to build a NodeJS application (e.g. with yarn build) and you get an error like this:

...
Linting and checking validity of types ... Failed to compile.
...
Type error: Property 'session' does not exist on type '{}'.
...

or you try to run your NodeJS application and you get an error like this:

error Command failed with exit code 3221225477

Potential Resolution

Check whether you have installed globally 32bit or 64bit NodeJS on your local system. Run the following command:


node -p "process.arch"


If you get ia32, it means you have installed a 32bit node globally and that might be the cause of the problem.


So, uninstall your globally installed node and install the 64bit version of NodeJS