Home > database >  How to use middlewares in custom middlewares in Node.js
How to use middlewares in custom middlewares in Node.js

Time:02-25

So I have this custom middleware that tries to get the cookie from the client. This is the declaration:

function auth(req, res, next) {}

But to access the cookies from the request, I need to use another middleware i.e. cookieParser. So now I have no ideas how can I use that cookieParser in my custom auth Middleware. Any help will be greatly appreciated.

CodePudding user response:

You do not use the middleware in your middleware. See the code bellow which should be fairly self-explanatory but i add some commments.

var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();

// add the cookie parser
app.use(cookieParser());

// your middleware
app.use(function auth(req, res, next) {
    // the cookie middleware above has processed the cookies
    // you access them like this

    console.log(req.cookies);
});

app.get('/', ...);

app.listen(8080)
  • Related