serve-static vs compression vs express-static-gzip
Static File Serving and Compression in Node.js Comparison
1 Year
serve-staticcompressionexpress-static-gzipSimilar Packages:
What's Static File Serving and Compression in Node.js?

Static file serving and compression are essential features in web development that enhance the performance and efficiency of web applications. Static file serving refers to the ability of a web server to deliver static assets such as HTML, CSS, JavaScript, images, and other files directly to clients without any server-side processing. Compression, on the other hand, is the process of reducing the size of these files before they are transmitted over the network, which helps to decrease load times and save bandwidth. Node.js provides various middleware and modules to handle static file serving and compression effectively, allowing developers to optimize their applications for faster content delivery.

Package Weekly Downloads Trend
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
serve-static39,344,1091,41025.7 kB1919 days agoMIT
compression21,185,8572,78727.5 kB212 months agoMIT
express-static-gzip133,60614924.4 kB35 months agoMIT
Feature Comparison: serve-static vs compression vs express-static-gzip

Compression

  • serve-static:

    serve-static is a middleware for serving static files from a specified directory. It does not perform any compression by default, but it provides a simple and flexible way to serve files while allowing customization of caching headers, directory listings, and more. It is the foundational static file serving middleware in Express, and it can be combined with other middleware (like compression) to enhance its functionality.

  • compression:

    compression middleware compresses HTTP responses using gzip, deflate, or Brotli algorithms. It automatically determines the best compression method based on the client's capabilities, reducing the size of the response data and improving load times. It is easy to integrate into Express applications and can be configured to compress only specific routes or file types, making it a versatile solution for enhancing performance.

  • express-static-gzip:

    express-static-gzip serves pre-compressed static files (gzip) alongside regular files. It allows you to specify a directory containing both compressed and uncompressed files, and the middleware will automatically serve the compressed version if the client supports it. This approach reduces the need for on-the-fly compression, resulting in faster response times and lower CPU usage, especially for static assets that do not change frequently.

Pre-compressed File Support

  • serve-static:

    serve-static does not handle pre-compressed files. It serves files as they are stored in the file system. If you want to serve pre-compressed files using serve-static, you would need to implement additional logic to check for the existence of compressed files and serve them accordingly.

  • compression:

    compression does not support serving pre-compressed files. It compresses responses on-the-fly based on the client's Accept-Encoding header. This means that the middleware compresses the data as it is being sent, which can save bandwidth but may increase CPU usage, especially for large files or high-traffic applications.

  • express-static-gzip:

    express-static-gzip is designed to serve pre-compressed files efficiently. It allows you to serve files that have already been compressed during the build process, which means the server does not need to perform any compression at runtime. This feature is particularly beneficial for static assets that are unlikely to change, as it reduces server load and speeds up response times by delivering the already-compressed files directly to the client.

Integration with Express

  • serve-static:

    serve-static is the core middleware used by Express to serve static files. It is highly customizable and can be configured to serve files from any directory. serve-static is a fundamental part of Express, and its functionality can be extended with additional middleware as needed.

  • compression:

    compression integrates seamlessly with Express applications. It can be added as middleware at the application level or for specific routes, allowing for flexible compression settings. The middleware is easy to configure and works well with other Express features, making it a popular choice for enhancing the performance of Express-based applications.

  • express-static-gzip:

    express-static-gzip is specifically designed for use with Express. It can be easily integrated into an Express application to serve pre-compressed static files. The middleware is straightforward to use and complements the existing static file serving capabilities of Express, providing an efficient way to deliver compressed assets.

Customization

  • serve-static:

    serve-static offers the most customization among the three packages. You can configure caching headers, enable or disable directory listings, set a custom file not found handler, and more. This flexibility makes serve-static a powerful tool for serving static files in a way that meets the specific needs of your application.

  • compression:

    compression provides limited customization options, such as setting the compression threshold, excluding certain routes or file types, and choosing the compression algorithm. However, it is primarily a black-box solution that automatically compresses responses based on the client's capabilities, with minimal configuration required.

  • express-static-gzip:

    express-static-gzip allows for more customization compared to compression, especially regarding how pre-compressed files are served. You can configure the middleware to specify the directory containing the compressed files, set caching headers, and control how the middleware handles requests for both compressed and uncompressed files.

Ease of Use: Code Examples

  • serve-static:

    To use serve-static in an Express application, you can do so directly as it is included with Express. Here’s a simple example:

    const express = require('express');
    const path = require('path');
    
    const app = express();
    
    // Serve static files from the 'public' directory
    app.use('/static', express.static(path.join(__dirname, 'public')));
    
    app.get('/', (req, res) => {
      res.send('Static File Serving with Express!');
    });
    
    app.listen(3000, () => {
      console.log('Server is running on http://localhost:3000');
    });
    

    This example demonstrates how to serve static files from a directory using the serve-static middleware, which is included in Express by default.

  • compression:

    To use compression middleware in an Express application, you need to install it first and then integrate it into your app. Here’s a simple example:

    const express = require('express');
    const compression = require('compression');
    
    const app = express();
    
    // Enable compression middleware
    app.use(compression());
    
    app.get('/', (req, res) => {
      res.send('Hello, World!');
    });
    
    app.listen(3000, () => {
      console.log('Server is running on http://localhost:3000');
    });
    

    This example demonstrates how to add gzip compression to all responses in an Express application using the compression middleware.

  • express-static-gzip:

    To use express-static-gzip in your Express application, you need to install it and then set it up to serve pre-compressed files. Here’s an example:

    const express = require('express');
    const { expressStaticGzip } = require('express-static-gzip');
    
    const app = express();
    
    // Serve pre-compressed static files from the 'public' directory
    app.use('/static', expressStaticGzip('public', {
      // Fallback to regular files if compressed files are not found
      fallback: true,
    }));
    
    app.get('/', (req, res) => {
      res.send('Welcome to the Express Static Gzip Example!');
    });
    
    app.listen(3000, () => {
      console.log('Server is running on http://localhost:3000');
    });
    

    In this example, the express-static-gzip middleware serves pre-compressed files from the public directory. If a compressed file is not available, it falls back to serving the regular file.

How to Choose: serve-static vs compression vs express-static-gzip
  • serve-static:

    Choose serve-static if you need a simple and flexible solution for serving static files from a directory. It is the core middleware used by Express to serve static assets, and it allows for customization of caching, directory listing, and more. However, it does not include compression out of the box.

  • compression:

    Choose compression if you want to add gzip compression to your entire Express application or specific routes easily. It is a middleware that automatically compresses responses based on the client's Accept-Encoding header, helping to reduce the size of the data sent over the network.

  • express-static-gzip:

    Choose express-static-gzip if you need to serve pre-compressed static files (gzip) alongside regular files. This package is particularly useful for applications that have already been optimized with gzip compression during the build process, allowing the server to deliver compressed files directly, which can further improve performance.

README for serve-static

serve-static

NPM Version NPM Downloads CI Test Coverage

Install

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install serve-static

API

var serveStatic = require('serve-static')

serveStatic(root, options)

Create a new middleware function to serve files from within a given root directory. The file to serve will be determined by combining req.url with the provided root directory. When a file is not found, instead of sending a 404 response, this module will instead call next() to move on to the next middleware, allowing for stacking and fall-backs.

Options

acceptRanges

Enable or disable accepting ranged requests, defaults to true. Disabling this will not send Accept-Ranges and ignore the contents of the Range request header.

cacheControl

Enable or disable setting Cache-Control response header, defaults to true. Disabling this will ignore the immutable and maxAge options.

dotfiles

Set how "dotfiles" are treated when encountered. A dotfile is a file or directory that begins with a dot ("."). Note this check is done on the path itself without checking if the path actually exists on the disk. If root is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when set to "deny").

  • 'allow' No special treatment for dotfiles.
  • 'deny' Deny a request for a dotfile and 403/next().
  • 'ignore' Pretend like the dotfile does not exist and 404/next().

The default value is 'ignore'.

etag

Enable or disable etag generation, defaults to true.

extensions

Set file extension fallbacks. When set, if a file is not found, the given extensions will be added to the file name and search for. The first that exists will be served. Example: ['html', 'htm'].

The default value is false.

fallthrough

Set the middleware to have client errors fall-through as just unhandled requests, otherwise forward a client error. The difference is that client errors like a bad request or a request to a non-existent file will cause this middleware to simply next() to your next middleware when this value is true. When this value is false, these errors (even 404s), will invoke next(err).

Typically true is desired such that multiple physical directories can be mapped to the same web address or for routes to fill in non-existent files.

The value false can be used if this middleware is mounted at a path that is designed to be strictly a single file system directory, which allows for short-circuiting 404s for less overhead. This middleware will also reply to all methods.

The default value is true.

immutable

Enable or disable the immutable directive in the Cache-Control response header, defaults to false. If set to true, the maxAge option should also be specified to enable caching. The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed.

index

By default this module will send "index.html" files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.

lastModified

Enable or disable Last-Modified header, defaults to true. Uses the file system's last modified value.

maxAge

Provide a max-age in milliseconds for http caching, defaults to 0. This can also be a string accepted by the ms module.

redirect

Redirect to trailing "/" when the pathname is a dir. Defaults to true.

setHeaders

Function to set custom headers on response. Alterations to the headers need to occur synchronously. The function is called as fn(res, path, stat), where the arguments are:

  • res the response object
  • path the file path that is being sent
  • stat the stat object of the file that is being sent

Examples

Serve files with vanilla node.js http server

var finalhandler = require('finalhandler')
var http = require('http')
var serveStatic = require('serve-static')

// Serve up public/ftp folder
var serve = serveStatic('public/ftp', { index: ['index.html', 'index.htm'] })

// Create server
var server = http.createServer(function onRequest (req, res) {
  serve(req, res, finalhandler(req, res))
})

// Listen
server.listen(3000)

Serve all files as downloads

var contentDisposition = require('content-disposition')
var finalhandler = require('finalhandler')
var http = require('http')
var serveStatic = require('serve-static')

// Serve up public/ftp folder
var serve = serveStatic('public/ftp', {
  index: false,
  setHeaders: setHeaders
})

// Set header to force download
function setHeaders (res, path) {
  res.setHeader('Content-Disposition', contentDisposition(path))
}

// Create server
var server = http.createServer(function onRequest (req, res) {
  serve(req, res, finalhandler(req, res))
})

// Listen
server.listen(3000)

Serving using express

Simple

This is a simple example of using Express.

var express = require('express')
var serveStatic = require('serve-static')

var app = express()

app.use(serveStatic('public/ftp', { index: ['default.html', 'default.htm'] }))
app.listen(3000)

Multiple roots

This example shows a simple way to search through multiple directories. Files are searched for in public-optimized/ first, then public/ second as a fallback.

var express = require('express')
var path = require('path')
var serveStatic = require('serve-static')

var app = express()

app.use(serveStatic(path.join(__dirname, 'public-optimized')))
app.use(serveStatic(path.join(__dirname, 'public')))
app.listen(3000)

Different settings for paths

This example shows how to set a different max age depending on the served file. In this example, HTML files are not cached, while everything else is for 1 day.

var express = require('express')
var path = require('path')
var serveStatic = require('serve-static')

var app = express()

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

app.listen(3000)

function setCustomCacheControl (res, file) {
  if (path.extname(file) === '.html') {
    // Custom Cache-Control for HTML files
    res.setHeader('Cache-Control', 'public, max-age=0')
  }
}

License

MIT