title: JWT error cannot read properties of undefined. req.user is always undefined after authenticate middleware
body: <p>I'm trying to create a redirect to the main dashboard by authorizing the token saved in sessionStorage from a new registration or login.  However, it seems that the authentication fails every time. It seems the error is because in the authenticate middleware, req.user = decoded is always undefined for some reason, but not sure why.</p>
  <pre><code>undefined
  TypeError: Cannot read properties of undefined (reading 'where')
      at exports.current (C:\Users\shmue\Desktop\AutoMotionParking\server\controllers\currentController.js:10:9)
  </code></pre>
  <p>here's the client-side Dashboard.js:</p>
  <pre><code>import axios from 'axios';
  import React, { useState, useEffect} from 'react';
  import {Link} from 'react-router-dom';
  import './DashboardPage.scss';
  
  function DashboardPage(){
  
      const API_KEY = 'd7740a55001340a7b39145833220706';
      const [currUser, setCurrUser] = useState('null');
      const [userInput, setUserInput] = useState('');
      const [location, setLocation] = useState(null);
      const [locationData, setlocationData] = useState(null);
      const [maxSortedLowToHi, setMaxSortedLowToHi] = useState(false);
      const [minSortedLowToHi, setMinSortedLowToHi] = useState(false);
      const [rainfallLowToHi, setRainfallLowToHi] = useState(false);
      const [todaysDateFirst, setTodaysDateFirst] = useState(true)
      const [failedAuth, setFailedAuth] = useState(false);
  
      useEffect(() =&gt; {
          const token = sessionStorage.getItem('token');
          if (!token) {
              setFailedAuth(true);
              return;
          }
          // Get the data from the API
          axios
              .get('http://localhost:8080/current', {
                  headers: {
                      authorization: 'Bearer ' + token
                  }
              })
              .then((response) =&gt; {
                  console.log(response);
                  setCurrUser(response.data.name);
              })
              .catch(() =&gt; {
                  setFailedAuth(true);
              });
      }, []);
  </code></pre>
  <p>here's the server-side routing</p>
  <p>index.js file</p>
  <pre><code>require('dotenv').config();
  const express = require('express');
  const cors = require('cors');
  const app = express();
  const registerRoute = require('./routes/registerRoute');
  const currentRoute = require('./routes/currentRoute');
  const loginRoute = require('./routes/loginRoute');
  const port = 8080;
  
  //middleware
  app.use(cors());
  app.use(express.json());
  
  //Routes
  app.use('/register', registerRoute);
  app.use('/current', currentRoute);
  app.use('/login', loginRoute);
  
  
  //port listener
  app.listen(port, () =&gt; {
    console.log(`Example app listening on port ${port}`)
  })
  </code></pre>
  <p>currentRoute.js file</p>
  <pre><code>const router = require('express').Router();
  const currentController = require('../controllers/currentController');
  
  router
      .route('/')
      .get(currentController.current);
  
  module.exports = router;
  </code></pre>
  <p>currentController.js is the file that checks if the current user trying to access the main dashboard is authenticated</p>
  <pre><code>const knex = require('knex')(require('../knexfile'));
  const authenticate = require('../middleware/authenticate');
  
  // [ROUTE] - &quot;/auth/current&quot;
  // [GET] - Gets currently logged in user to validate JWT authentication
  exports.current = (authenticate, (req, res) =&gt; {
    
      knex('users')
          console.log(req.user) ***prints undefined***
          .where({ email: req.user.email })
          .first()
          .then((user) =&gt; {
              // Respond with the user data
              delete user.password;
              res.json(user);
          });
  });
  </code></pre>
  <p>authenticate middleware</p>
  <pre><code>const jwt = require('jsonwebtoken');
  const authenticate = (req, res, next) =&gt; {
      // If there is no auth header provided
      if (!req.headers.authorization) {
          return res.status(401).send(&quot;Please login&quot;);
      }
  
      // Parse the Bearer token
      const authToken = req.headers.authorization.split(&quot; &quot;)[1];
      
      // Verify the token
      jwt.verify(authToken, process.env.JWT_KEY, (err, decoded) =&gt; {
          // Sends 401 status if JWT not valid
          if (err) {
              return res.status(401).send(&quot;Invalid auth token&quot;);
          } 
          req.user = decoded;
          next();
      })
  
  }
  module.exports = authenticate;
  </code></pre>