Mastering Serve Static A Comprehensive Guide with Examples

Introduction to Serve Static

serve-static is a middleware for serving static files with Node.js and Express applications. It’s a core part of web development, allowing you to serve images, CSS files, and JavaScript files to clients.

How to Use Serve Static

  const express = require('express');
  const serveStatic = require('serve-static');
  const path = require('path');
  
  const app = express();

  // Serve static files from the 'public' directory
  app.use(serveStatic(path.join(__dirname, 'public')));

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

API Examples

Basic Usage

  const express = require('express');
  const serveStatic = require('serve-static');
  const path = require('path');
  
  const app = express();
  app.use(serveStatic(path.join(__dirname, 'public')));
  app.listen(3000);

Serving Multiple Directories

  app.use('/static', serveStatic(path.join(__dirname, 'public')));
  app.use('/media', serveStatic(path.join(__dirname, 'media')));

Setting Cache Control Headers

  app.use(serveStatic(path.join(__dirname, 'public'), {
    maxAge: '1d'
  }));

Using Redirect for Directories

  app.use(serveStatic(path.join(__dirname, 'public'), {
    redirect: false
  }));

Fallthrough Option

  app.use(serveStatic(path.join(__dirname, 'public'), {
    fallthrough: false
  }));

Custom Index File

  app.use(serveStatic(path.join(__dirname, 'public'), {
    index: 'homepage.html'
  }));

Hidden Files

  app.use(serveStatic(path.join(__dirname, 'public'), {
    dotfiles: 'allow'
  }));

App Example with Serve Static

  const express = require('express');
  const serveStatic = require('serve-static');
  const path = require('path');

  const app = express();

  // Serve static files
  app.use(serveStatic(path.join(__dirname, 'public')));

  // Example route
  app.get('/api/example', (req, res) => {
    res.json({ message: 'Hello world!' });
  });

  // Starting the server
  app.listen(3000, () => {
    console.log('Server is running on port 3000');
  });

Embed serve-static in your application and serve files efficiently and effectively!

Hash: 6549a137ec232549950d4fdb8e19a1090272d0dff43ae3b908a39fb9ffc1593f

Leave a Reply

Your email address will not be published. Required fields are marked *