Farzher
Farzher

Reputation: 14563

Node.js Express: Execute hook on every HTTP request, before app.get() and app.post()?

I don't want to put an authentication function at the top of every app.get(), how can I execute code on every request, before app.get()?

Upvotes: 27

Views: 17793

Answers (2)

chovy
chovy

Reputation: 75666

You can also do:

app.all('*', auth.requireUser);

Upvotes: 7

hhh
hhh

Reputation: 2769

Set up a middleware before your routes:

function myMiddleware (req, res, next) {
   if (req.method === 'GET') { 
     // Do some code
   }

   // keep executing the router middleware
   next()
}

app.use(myMiddleware)

// ... Then you load the routes

Upvotes: 54

Related Questions