Express - Serve Static Assets: Why doesn't the first argument of app.use take the absolute path?


Just a quick technical question.

While completing this challenge, I discovered that the stylesheet won’t load correctly if you pass app.use the absolute path (__dirname + "/public") as opposed to just "/public" for the first argument.

I was wondering why this is? Just out of curiosity. I tried searching online but couldn’t find anything about this in documentation. Maybe I’m just not looking for the right thing?

Can you share the full line of code you are talking about?

You got it:

app.use("/public", express.static(__dirname + "/public")); (works)

app.use((__dirname + "/public"), express.static(__dirname + "/public")); (does not work)

The folder that is given to express.static becomes the base directory.

If you do not mount it to /public the path in the HTML file /public/style.css is wrong as it would just be ./style.css (or just style.css).

For example, for the file path




…would give you this path to the file.


The first argument to app.use is a virtual mount path. For example, we can use static, which is a folder that does not exist.

app.use('/static', express.static('public'))

Now the CSS file inside the public folder can be used as if it was in a static folder


<link rel="stylesheet" href="/static/style.css">

1 Like