title: How to have Express.js server file using router path as root?
body: <p>I have a directory structure like this</p>
  
  <pre><code>root
    private
      js
      css
      index.html
    app.js
    privateRouter.js
    ...
  </code></pre>
  
  <p>In my index.html I reference the js and css files using relative path like this:</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;link rel="stylesheet" href="css/index.css"/&gt;
  &lt;script src="js/index.js"&gt;&lt;/script&gt;
  </code></pre>
  
  <p>On the server side I have a private router checks for authentication before serving these files:</p>
  
  <p>In app.js:</p>
  
  <pre class="lang-js prettyprint-override"><code>app.use("/private", privateRouter);
  </code></pre>
  
  <p>in privateRouter.js:</p>
  
  <pre class="lang-js prettyprint-override"><code>router.use((req, res, next) =&gt; {
      isAuthenticated(req) ? next() : res.redirect("/");
  });
  
  router.get('/', function(req, res, next) {
      res.sendFile(require('path').join(__dirname + "/private/index.html"));
  });
  </code></pre>
  
  <p>So now if I visit <code>http://mywebsite.com/private</code> I will get the the index.html, but the request of js/css files from the browser comes back to the server as <code>http://mywebsite.com/js</code> instead of <code>http://mywebsite.com/private/js</code>, thus returns file not found.</p>
  
  <p>Alternatively if I serve files statically, the browser knows to request from <code>/private/js</code>:</p>
  
  <pre class="lang-js prettyprint-override"><code>app.use("/private", express.static(path.join(__dirname, 'private')));
  </code></pre>
  
  <p>But I can't server statically because I need to authenticate specific files and not serve all files publicly. And I don't want to have to append <code>private/</code> before all file references on client side. I don't understand why when serving statically the server knows to use <code>/private</code> as root but when using a router it uses <code>/</code> as root.</p>
  
  <p><strong>How can I keep the url as <code>http://mywebsite.com/private</code> while not having to append <code>private/</code> in all file references on the client side?</strong></p>
  
  <p>I'm new to express.js and it was also difficult for me to formulate the question. I think I'm fundamentally misunderstanding something about express.js works. Thanks for your help!</p>