0
0
Expressframework~5 mins

Why serving static files matters in Express

Choose your learning style9 modes available
Introduction

Serving static files lets your web app show images, styles, and scripts to users. Without it, your site would look plain and not work well.

You want to show pictures or logos on your website.
You need to apply styles with CSS to make your site look nice.
You want to add JavaScript files to make your site interactive.
You have downloadable files like PDFs or documents for users.
You want to serve fonts or icons for better design.
Syntax
Express
app.use(express.static('public'))
This tells Express to serve all files inside the 'public' folder as static files.
Users can access these files directly via URLs matching their path inside 'public'.
Examples
Serve static files from the 'assets' folder instead of 'public'.
Express
app.use(express.static('assets'))
Serve static files from 'public' but under the '/static' URL path.
Express
app.use('/static', express.static('public'))
Sample Program

This Express app serves files from the 'public' folder. When you visit the home page, it shows a heading and an image loaded from '/logo.png' inside 'public'.

Express
import express from 'express';
const app = express();

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

app.get('/', (req, res) => {
  res.send('<h1>Welcome!</h1><img src="/logo.png" alt="Logo">');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Make sure your static files are in the folder you specify (like 'public').

Static middleware should be set before routes that might conflict with file paths.

Summary

Serving static files is essential to show images, styles, and scripts on your site.

Express makes it easy with express.static middleware.

Organize your static files in a folder and tell Express to serve them.