Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Express Basics (2015) Serving Static Files in Express Setting Up the Express Static Server in Development

Why do we have to use express.static and not app.static?

Houston mentions that this is one of the cases where you have to use express.static as a parameter in app.use().

But he never explains why. What happens if we use app.static?

If app just accesses express(), what's the difference?

1 Answer

Matt Milburn
Matt Milburn
20,786 Points

express.static() is a built-in to Express itself, not an instance of Express (i.e. app). It handles serving static files such as images, fonts, styles and scripts through Express. If we do not use this function to specify the location of this directory to Express, it won't know where to find those resources.

For example, in my stylesheets on my server, which are also stored in my static directory, I can set the file path to an image to something like url("images/example.jpg"). Since we used app.use(express.static('public')) to specify the location of our static directory in Express, the server will look for this image in the public directory from the server's root... which means it will look for the image in /public/images/example.jpg - exactly where my image is located.

But why doesn't Express know to do this by default?

Express does not assume what you want. You may want to store your static resources in a directory called static instead of public or you may want to specify multiple static directories instead of just one.

If it's still not making sense, don't worry. Many things in the programming world do not make sense to the programmer at first. Just trust it and go with it until the future gives you reason to do it differently or you discover the true reasoning for its existence.