0
0
ExpressHow-ToBeginner · 3 min read

How to Serve Images in Express: Simple Guide

To serve images in Express, use the express.static middleware to expose a folder with image files. Then, access images via URLs matching the folder path, letting Express deliver them automatically.
📐

Syntax

The main syntax to serve images in Express is using express.static middleware. You provide the folder path where images are stored, and Express serves files from there.

  • express.static(path): Middleware to serve static files from the given path.
  • app.use('/url-path', express.static('folder-path')): Mounts the static middleware at /url-path, serving files from folder-path.
javascript
const express = require('express');
const app = express();

// Serve static files from 'public' folder at root URL
app.use(express.static('public'));

// Or serve static files from 'images' folder at '/images' URL
app.use('/images', express.static('images'));
💻

Example

This example shows how to serve images placed in a folder named images. When you visit http://localhost:3000/images/photo.jpg, Express will send the photo.jpg file from the images folder.

javascript
const express = require('express');
const app = express();
const port = 3000;

// Serve images from 'images' folder at '/images' URL
app.use('/images', express.static('images'));

app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});
Output
Server running at http://localhost:3000
⚠️

Common Pitfalls

Common mistakes when serving images in Express include:

  • Not using express.static middleware, which means Express won't serve files automatically.
  • Incorrect folder path or URL path causing 404 errors.
  • Placing images outside the served folder, so they are not accessible.
  • Forgetting to restart the server after adding new images.

Example of a wrong and right way:

javascript
// Wrong way: Trying to send image file manually without static middleware
const path = require('path');
app.get('/image', (req, res) => {
  res.sendFile(path.join(__dirname, 'images', 'photo.jpg'));
});

// Right way: Use express.static middleware
app.use('/images', express.static('images'));
📊

Quick Reference

ConceptDescriptionExample
express.staticMiddleware to serve static filesapp.use('/images', express.static('images'))
Folder pathLocal folder containing images'images'
URL pathURL prefix to access images'/images/photo.jpg'
File accessAccess image by URL matching file namehttp://localhost:3000/images/photo.jpg

Key Takeaways

Use express.static middleware to serve images from a folder.
Mount the static middleware at a URL path to organize access.
Ensure the folder path is correct and images are inside it.
Access images via URLs matching the folder and file names.
Restart the server after adding or changing image files.