Olesia
Olesia

Reputation: 11

ExpressJwt is not a function

I'm trying to write user authorization middleware. I use this function to validate and verify authorization later on.

I have done yarn add express-jwt.

auth.js code:

const SECRET = 'secret-message';

const jwt = require('jsonwebtoken');
const expressJwt  = require('express-jwt');
const compose = require('composable-middleware');

function sign(user) {
    return jwt.sign({
        _id: user._id,
    }, SECRET, {
        expiresIn: 60 * 60
    });
}

function sendUnauthorized(req, res) {
    console.log(req.headers.authorization);
    console.log(req.user);
    res.status(401).json ({ message: 'Unathorized' });
};

const validateJwt = expressJwt({
    secret: SECRET,
    fail: sendUnauthorized,
    getToken(req) {
        if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
            return req.headers.authorization.split(' ')[1];
        } else if (req.query && req.query.access_token) {
            return req.query.access_token;
        }
        return null;
    }
});

And the error is:

const validateJwt = expressJwt({
                    ^

TypeError: expressJwt is not a function

I'm stuck on this error and can't go any further. I really need some advice.

Upvotes: 1

Views: 1908

Answers (1)

CherryDT
CherryDT

Reputation: 29011

As the error says, expressJwt is not a function. The logical next step would then be to check what it is instead, and at the same time to recheck your assumption of it being a function (why do you think that?) and looking for sources for that, for example by checking the docs of the package.

You will find that a) it's an object with { expressjwt: <some function here> }, and b) that the docs show an example that uses destructuring (var { expressjwt: jwt } = require('express-jwt')) which you don't do.

Both of these findings should point you to the fact that your assumption of the module's default export being a function is wrong and it's instead an object with property expressjwt which is the function you are looking for, so you could fix your code by using destructuring on the import as follows:

const { expressjwt: expressJwt } = require('express-jwt');

(Alternatively, using expressJwt.expressjwt(...) would have worked too, of course, but I think it looks quite ugly and is unnecessarily verbose.)

Upvotes: 3

Related Questions