serve-static vs express vs koa-static
Serving Static Assets in Node.js Web Applications
serve-staticexpresskoa-staticSimilar Packages:
Serving Static Assets in Node.js Web Applications

express, koa-static, and serve-static are all used to serve static files (like HTML, CSS, JS, images) from a Node.js server, but they belong to different ecosystems and serve distinct architectural roles. express is a full-featured web framework that includes routing, middleware, and request handling. serve-static is a dedicated Express-compatible middleware for serving static files. koa-static is the equivalent middleware for the Koa framework, which follows a more minimal and modern async/await-based design. While express can serve static files using serve-static, it is not its primary purpose — similarly, koa-static only works within a Koa application.

Npm Package Weekly Downloads Trend
3 Years
Github Stars Ranking
Stat Detail
Package
Downloads
Stars
Size
Issues
Publish
License
serve-static55,836,8241,41625.7 kB218 months agoMIT
express54,728,85568,30175.4 kB2203 days agoMIT
koa-static913,2371,144-117 years agoMIT

Serving Static Assets: express vs koa-static vs serve-static

When you need to deliver HTML, JavaScript, CSS, images, or other static files from a Node.js backend, your choice of tool depends heavily on your application’s architecture. The packages express, koa-static, and serve-static are often mentioned together, but they solve different problems at different layers. Let’s clarify what each does — and when to use which.

🧱 Core Roles: Framework vs Middleware

express is a full web application framework. It handles routing, middleware, request parsing, and response formatting. While it can serve static files, it delegates that job to middleware like serve-static.

// express alone cannot serve static files efficiently
// You must use serve-static as middleware
import express from 'express';
const app = express();

// This won't work without serve-static
// app.use(express.static('public')); // actually uses serve-static under the hood

💡 Note: express.static is just an alias for serve-static. When you call express.static(), you’re using the serve-static package.

serve-static is a standalone middleware designed specifically to serve static files. It works with Express, Connect, or any framework that follows the (req, res, next) middleware signature.

// Using serve-static directly (though usually via express.static)
import serveStatic from 'serve-static';
import finalhandler from 'finalhandler';
import http from 'http';
import fs from 'fs';

const serve = serveStatic('public', { index: ['index.html'] });

const server = http.createServer((req, res) => {
  serve(req, res, finalhandler(req, res));
});

koa-static is the Koa-specific equivalent of serve-static. It only works in Koa applications and leverages Koa’s context (ctx) object and async middleware model.

// koa-static in a Koa app
import Koa from 'koa';
import serve from 'koa-static';

const app = new Koa();
app.use(serve('public'));

⚙️ How Static Serving Actually Works

None of these packages are “static servers” by themselves — except when composed properly. Here’s how each is typically used:

With Express (using serve-static under the hood)

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

// This is the standard way
app.use(express.static('public', {
  maxAge: '1d',
  etag: true,
  fallthrough: false
}));

app.listen(3000);

Under the hood, express.static = require('serve-static'). So you’re really using serve-static.

With Koa (using koa-static)

import Koa from 'koa';
import serve from 'koa-static';

const app = new Koa();
app.use(serve('public', {
  maxage: 86400000, // 1 day in ms
  hidden: false,
  index: 'index.html'
}));

app.listen(3000);

Standalone with serve-static (no framework)

import http from 'http';
import serveStatic from 'serve-static';
import finalhandler from 'finalhandler';
import path from 'path';

const serve = serveStatic(path.join(process.cwd(), 'public'), {
  index: ['index.html']
});

http.createServer((req, res) => {
  serve(req, res, finalhandler(req, res));
}).listen(3000);

🔒 Important: serve-static requires a final handler (like finalhandler) to manage 404s and errors in standalone mode.

🛠️ Feature Comparison: Caching, Security, and Control

All three approaches support common static-serving needs, but through different APIs.

Setting Cache Headers

Express / serve-static:

app.use(express.static('public', {
  maxAge: '7d',
  etag: true
}));

Koa / koa-static:

app.use(serve('public', {
  maxage: 7 * 24 * 60 * 60 * 1000, // 7 days in ms
  immutable: true
}));

Note the spelling difference: maxAge (serve-static) vs maxage (koa-static).

Handling Hidden Files

serve-static hides dotfiles by default (dotfiles: 'ignore'). You can allow them:

express.static('public', { dotfiles: 'allow' })

koa-static also hides them by default (hidden: false). Enable with:

serve('public', { hidden: true })

Custom Index Files

Both let you define fallback index files:

// serve-static
express.static('public', { index: ['default.html', 'index.html'] })

// koa-static
serve('public', { index: 'default.html' }) // only accepts string, not array

⚠️ Limitation: koa-static only supports a single index filename, while serve-static accepts an array for fallbacks.

🔄 Framework Compatibility: Don’t Mix Ecosystems

  • serve-static works with Express, Connect, or any (req, res, next) middleware system. It does not work with Koa.
  • koa-static only works with Koa. It will throw errors if used in an Express app.
  • express is a complete framework — you don’t “add” it to Koa or vice versa.

Trying to use koa-static in Express:

// ❌ This fails
import express from 'express';
import koaStatic from 'koa-static';

const app = express();
app.use(koaStatic('public')); // TypeError: ctx is not defined

Similarly, serve-static won’t work in Koa without adaptation:

// ❌ This also fails
import Koa from 'koa';
import serveStatic from 'serve-static';

const app = new Koa();
app.use(serveStatic('public')); // Doesn't match Koa's async middleware signature

🧪 When to Use What: Real Scenarios

Scenario 1: Building a Full REST API + Frontend Bundle

You have an Express backend serving JSON APIs and also need to deliver a React SPA.

  • Use: express + express.static() (i.e., serve-static)
  • Why? Tight integration, same codebase, easy routing precedence control.
app.use('/api/users', userRoutes);
app.use(express.static('build')); // serves index.html for SPA

Scenario 2: Lightweight Koa Microservice with Static Docs

You’re using Koa for its async simplicity and need to serve Swagger UI or docs.

  • Use: koa-static
  • Why? Native Koa middleware, no extra abstraction layer.
app.use(serve('docs'));

Scenario 3: Minimal Static File Server (No Routing Needed)

You just want to serve a folder over HTTP with caching and gzip.

  • Use: serve-static directly with Node’s http module
  • Why? Avoid framework overhead; serve-static is battle-tested for this exact use case.

🚫 Common Misconceptions

  • Myth: “express serves static files natively.”

    • Truth: It relies entirely on serve-static via express.static.
  • Myth: “koa-static is a drop-in replacement for serve-static.”

    • Truth: They belong to incompatible middleware systems.
  • Myth: “I can use serve-static in Koa with a wrapper.”

    • Truth: Possible, but not recommended — use koa-static instead for cleaner code.

📊 Summary Table

PackageTypeFramework RequiredInput ShapeKey Strength
expressFull frameworkNone (it is the framework)N/AEnd-to-end app development
serve-staticMiddlewareExpress/Connect(req, res, next)Production-grade static serving
koa-staticMiddlewareKoactx, nextClean integration with Koa apps

💡 Final Guidance

  • If you’re using Express, serve static files with express.static() — which is serve-static.
  • If you’re using Koa, reach for koa-static.
  • Never use express just to serve static files — that’s overkill. Use serve-static standalone or with a minimal server.
  • Never mix middleware across ecosystems — it leads to runtime errors and maintenance headaches.

The right choice isn’t about which package is “better” — it’s about matching the tool to your application’s foundation. Get that right, and static asset delivery becomes a solved problem.

How to Choose: serve-static vs express vs koa-static
  • serve-static:

    Choose serve-static when you need a robust, production-ready static file server that integrates with Express (or any Connect-compatible framework). It offers fine-grained control over caching, directory listing, and file resolution. Use it as middleware within an Express app — not as a standalone server.

  • express:

    Choose express if you're building a full web application or API that requires routing, middleware composition, error handling, and other server-side features beyond just serving static files. It’s ideal when you need an all-in-one solution with a mature ecosystem and extensive third-party middleware support. Don’t use it solely for static file serving — pair it with serve-static for that task.

  • koa-static:

    Choose koa-static only if you’re already using the Koa framework and need to serve static assets. It integrates cleanly with Koa’s middleware pipeline and async/await pattern. Avoid it if you’re not using Koa — it won’t work with Express or standalone servers.

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