skip to Main Content

I’m building my first API web project and I have encountered an error:

return expressJwt({
           ^
TypeError: expressJwt is not a function

This is my code :

const expressJwt = require('express-jwt');

function authJwt() {
    const secret = process.env.secret;

    return expressJwt({
        secret,
        algorithms: ['HS256'],
    })

3

Answers


  1. you are not using correctly espress-jwt when you do

    const expressJwt = require(‘express-jwt’);

    You are importing the all library, however, you need specifically expressJwt method, so you can do something like

    const expressJwt = require('express-jwt');
    
    function authJwt() {
        const secret = process.env.secret;
    
        return expressJwt.expressJwt({
            secret,
            algorithms: ['HS256'],
        })
    

    Or even better, as explained in the official documentation

    const { expressJwt: jwt } = require('express-jwt');
    
    function authJwt() {
        const secret = process.env.secret;
    
        return jwt({
            secret,
            algorithms: ['HS256'],
        })
    
    Login or Signup to reply.
  2. Since you are importing the whole module, you have to specify the method to use. For example:

    const expressJwt = require('express-jwt');
    
    function authJwt() {
        const secret = process.env.secret;
    
        return expressJwt.expressjwt({
            secret,
            algorithms: ['HS256'],
        })
      }
    
    Login or Signup to reply.
  3. When you import a module in Node.js you need to know what is being exported by the module.

    You are using the express-jwt module with CommonJS syntax which exports an object with a key of expressjwt and the value of which is a function named expressjwt. It looks like this:

    exports.expressjwt = expressjwt;
    
    // This is what's exported: { expressjwt: expressjwt }
    

    If you want to use the expressjwt function then you can use object destructing to import it like so:

    const { expressjwt } = require("express-jwt");
    

    If you want to rename the expressjwt function when you import it you can. The official docs give an example of renaming it to jwt like this:

    var { expressjwt: jwt } = require("express-jwt");
    

    To get your code working you can rename expressjwt to expressJwt very easily like this:

    const { expressjwt: expressJwt } = require("express-jwt");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search