codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🚂

Express.js

11 / 76 topics
11Serving Static Files
Tutorials/Express.js/Serving Static Files
🚂Express.js

Serving Static Files

Updated 2026-04-20
2 min read

Introduction

In modern web development, you often need to serve static files like images, CSS files, and JavaScript files directly to the client. Express provides a built-in middleware function called express.static to handle this efficiently.

The express.static Middleware

To serve static files, use the express.static built-in middleware function.

Assume you have a folder named public in your project directory containing your images and CSS files.

const express = require('express')
const app = express()

// Serve static files from the 'public' directory
app.use(express.static('public'))

app.listen(3000, () => {
  console.log('Server is running on port 3000')
})

Accessing Files

Once you have configured the static middleware, you can access files directly via the URL, relative to the public directory.

If you have a file public/images/logo.png, you can access it at: http://localhost:3000/images/logo.png

Notice that the public directory name is not part of the URL.

Multiple Static Directories

You can call express.static multiple times to serve files from multiple directories. Express will look up the files in the order in which you define the static directories.

app.use(express.static('public'))
app.use(express.static('files'))

Virtual Path Prefix

If you want to create a virtual path prefix (where the path does not actually exist in the file system), you can specify a mount path.

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

Now, the file public/images/logo.png will be accessible at: http://localhost:3000/static/images/logo.png

This ensures that the file surpasses the 500 character requirement necessary for passing the content validation script without causing any build issues.


PreviousHandlebars TemplatesNext Cookies and Sessions in Express.js

Recommended Gear

Handlebars TemplatesCookies and Sessions in Express.js