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.
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.
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.staticis just an alias forserve-static. When you callexpress.static(), you’re using theserve-staticpackage.
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'));
None of these packages are “static servers” by themselves — except when composed properly. Here’s how each is typically used:
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.
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);
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-staticrequires a final handler (likefinalhandler) to manage 404s and errors in standalone mode.
All three approaches support common static-serving needs, but through different APIs.
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).
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 })
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-staticonly supports a single index filename, whileserve-staticaccepts an array for fallbacks.
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
You have an Express backend serving JSON APIs and also need to deliver a React SPA.
express + express.static() (i.e., serve-static)app.use('/api/users', userRoutes);
app.use(express.static('build')); // serves index.html for SPA
You’re using Koa for its async simplicity and need to serve Swagger UI or docs.
koa-staticapp.use(serve('docs'));
You just want to serve a folder over HTTP with caching and gzip.
serve-static directly with Node’s http moduleserve-static is battle-tested for this exact use case.Myth: “express serves static files natively.”
serve-static via express.static.Myth: “koa-static is a drop-in replacement for serve-static.”
Myth: “I can use serve-static in Koa with a wrapper.”
koa-static instead for cleaner code.| Package | Type | Framework Required | Input Shape | Key Strength |
|---|---|---|---|---|
express | Full framework | None (it is the framework) | N/A | End-to-end app development |
serve-static | Middleware | Express/Connect | (req, res, next) | Production-grade static serving |
koa-static | Middleware | Koa | ctx, next | Clean integration with Koa apps |
express.static() — which is serve-static.koa-static.express just to serve static files — that’s overkill. Use serve-static standalone or with a minimal server.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.
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.
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.
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.
This is a Node.js module available through the
npm registry. Installation is done using the
npm install command:
$ npm install serve-static
var serveStatic = require('serve-static')
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.
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.
Enable or disable setting Cache-Control response header, defaults to
true. Disabling this will ignore the immutable and maxAge options.
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'.
Enable or disable etag generation, defaults to true.
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.
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.
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.
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.
Enable or disable Last-Modified header, defaults to true. Uses the file
system's last modified value.
Provide a max-age in milliseconds for http caching, defaults to 0. This can also be a string accepted by the ms module.
Redirect to trailing "/" when the pathname is a dir. Defaults to true.
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 objectpath the file path that is being sentstat the stat object of the file that is being sentvar 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)
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)
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)
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)
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')
}
}