title: Securing Express route with JWT
body: <p>I am new to JWT authentication and I need to secure an Express route. Before adding the auth I did the following to return an HTML page using Express:</p>
  <pre><code>var cache = {};
  
  app.get('/my_page', function (req, res) {
      serveStatic(res, cache, './public/default/my_page.html');
  });
  </code></pre>
  <p>where serveStatic is:</p>
  <pre><code>var send404 = function (response) {
      response.writeHead(404, {'Content-Type': 'text/plain'});
      response.write('Error 404: Resource not found.');
      response.end();
  }
  
  var sendFile = function(response, filePath, fileContents) {
      var mimeType = mime.lookup(path.basename(filePath));
      response.writeHead(200, {&quot;content-type&quot;: mimeType});
      response.end(fileContents);
  }
  
  var serveStatic = function(response, cache, absPath) {
      if (cache[absPath]) {
          sendFile(response, absPath, cache[absPath]);
      } else {
          fs.exists(absPath, function(exists) {
              if (exists) {
                  fs.readFile(absPath, function(err, data) {
                      if (err) {
                          send404(response);
                      } else {
                          cache[absPath] = data; // Cache the file
                          sendFile(response, absPath, data); // Serve the file
                      }
                  });
              } else {
                  send404(response);
              }
          });
      }
  }
  </code></pre>
  <p>Users clicked a button to access the page: <code>&lt;button type=&quot;button&quot; onclick=&quot;window.location='my_page'&quot;&gt;Go&lt;/button&gt;</code></p>
  <p>I added authentication as follows:</p>
  <pre><code>// In /middleware/auth file
  const jwt = require(&quot;jsonwebtoken&quot;);
  const dotenv = require('dotenv');
  dotenv.config();
  
  module.exports = function(req, res, next) {
      const token = req.header(&quot;Authorization&quot;);
  
      if (!token) {
          return res.status(401).json({
              message: &quot;Auth Error&quot;,
              errorCode: 401,
              redirectUrl: &quot;/&quot;
          });
      }
      
      try {
          const decoded = jwt.verify(token, process.env.SECRET);
          req.user = decoded.user;
          next();
      } catch (e) {        
          res.status(500).send({
              message: &quot;Invalid Token&quot;,
              errorCode: 500,
              redirectUrl: &quot;/&quot;
          });
      }
  };
  </code></pre>
  <p>I changed the route management as:</p>
  <pre><code>const auth = require(&quot;./middleware/auth&quot;);
  
  app.get('/licenses',
      auth,
      function (req, res, next) {
          serveStatic(res, cache, './public/default/my_page.html');
      }
  );
  
  </code></pre>
  <p>and I changed the button onclick to call a function that retrieves the JWT from the cookie and sends it with the request.</p>
  <pre><code>&lt;button type=&quot;button&quot; onclick=&quot;openPage()&quot;&gt;Go&lt;/button&gt;
  </code></pre>
  <pre><code>var openPage= function() {
      if (document.cookie != &quot;&quot;) {
          var token = getCookie(&quot;token&quot;);
  
          if (token != &quot;&quot;) {
              $.ajax({
                  type: &quot;GET&quot;,
                  url: &quot;/my_page&quot;,
                  data: {},
                  dataType: &quot;json&quot;,
                  beforeSend: function (xhr){ 
                      xhr.setRequestHeader('Authorization', token); 
                  },
                  success: function(msg) {
                      
                  },
                  error: function($xhr, textStatus, errorThrown) {
                      
                  }
              });
          } else {
              console.error('token is empty');
          }
      } else {
          console.error('cookie is empty');
      }
  }
  </code></pre>
  <p>The auth process is fine, but the client receives a message containing the my_page.html code in its responseText property. Is there a way to make it behave like it was before I added the auth?</p>