MyInternships.in

Express.js & REST APIs

Node.js Express Static Files

express.static serves files from a directory directly — images, CSS, a built front end. It handles content types, caching headers and range requests for you.


What is Express Static Files in Node.js?

express.static serves files from a directory directly — images, CSS, a built front end. It handles content types, caching headers and range requests for you.

Express Static Files example

Serving assets and an SPA
JavaScript
app.use(express.static('public', { maxAge: '1d' }));

// serve a built React/Angular app and support client-side routing
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});

Key points to remember

  • Register static middleware before the catch-all route.
  • Set a long maxAge for hashed asset filenames.
  • In production, a CDN or Nginx serves static files faster than Node.

Common mistakes with Express Static Files

  • Exposing a directory containing uploads or configuration files.
  • The SPA catch-all placed before the API routes, so it swallows every request.

Node.js Express Static Files— Interview Questions & FAQs

How do I serve a React build from Express?+

Serve the build directory with express.static, then add a catch-all route that returns index.html so client-side routes resolve. Register both after your API routes.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships