MateuszWawrzynski
MateuszWawrzynski

Reputation: 1331

Express.js on every request event?

I was wonder if something like expained below even exist?
Is it possible to make "middle execute" condition using express.js?
I know it is difficult to explain, but look at the code below.

Imagine we have simple API using express:

const app = require('express')

app.get('/endpoint', (request, response) => {
    // code
    response.status(200)
})
app.get('/endpoint2', (request, response) => {
    // code
    response.status(200)
})

Good. Now I want to authenticate every user which try to request ANY endpoint. Imagine example function below:

// pesudo code

// GET /endpoint2 for example
app.onEvent('request', (request, response) => {
    // some code
    if(something == true){
        // go ahead, execute your request
        request.execute() // redirect to app.get('/endpoint2', ...
    }
    else {
        // authentication failed
        response.status(401).message('Wrong API key or something')
    }
})


// pesudo code

I think I explained it clearly. Thanks for any help.

Upvotes: 0

Views: 917

Answers (2)

Rohit Singh
Rohit Singh

Reputation: 184

You can write any function like this for verification

function verify(req, res, next) {
  const bearerHeader = req.headers["authorization"];
  if (typeof bearerHeader !== "undefined") {
    console.log("Auth token", bearerHeader);
  } else {
    res.status(403);
  }
  next();
}

the above one is an example which checks for the Authorization header in the request. You can write your own conditions. If condition doesn't meet return.

res.status(403)

and in every request just add this middleware function for verification

app.get('/endpoint', verify,(request, response) => {
    // code
    response.status(200)
})
app.get('/endpoint2',verify, (request, response) => {
    // code
    response.status(200)
})

This will check the call the verification method first and it will verify the written condition and in case of failure it will just return 403 status code and if it pass then

next()

function will get trigger

Upvotes: 1

Quentin
Quentin

Reputation: 943556

This is called middleware.

Write a function that takes a request, response and next arguments.

Call next() when it is done (unless you want to send a response (like Forbidden) instead).

Pass it to use.

app.use(yourMiddleware);

It's covered on the second page of the Express.js guide

Upvotes: 2

Related Questions