`egg-static` is a core plugin for the Egg.js Node.js framework, providing robust static file serving capabilities. It is built upon `koa-static-cache`, inheriting its efficient caching and serving mechanisms. The plugin is usually enabled by default in Egg.js applications, simplifying the process of making static assets available. Currently, the `2.x` series is stable, with `v2.3.1` released in February 2023. A significant `v3.0.0` release in January 2025 introduced breaking changes, primarily dropping support for older Node.js versions (below 18.19.0). Its release cadence is generally tied to the Egg.js framework's development. Key differentiators include its seamless integration with the Egg.js ecosystem, intelligent default caching behaviors optimized for both development and production environments, and flexible configuration for handling multiple static directories with custom URL prefixes.
npm install egg-staticVerified import paths — ran on the pinned version, not inferred.
This code demonstrates how to enable and configure `egg-static` in a minimal Egg.js application. It sets up a `/public/` prefix serving files from `app/public`, with different caching strategies for development and production.
Ensure your Node.js environment is at version `18.19.0` or higher before upgrading to `egg-static@3.0.0`. If you cannot upgrade Node.js, remain on `egg-static@2.x`.
To see changes to static files in production, you must restart your Egg.js application. During development, `maxAge` is typically set to `0` (no cache) to allow immediate changes.
Always verify that the `prefix` in `config.static` matches the URL path you are requesting and that the `dir` correctly points to the actual location of your static files on the filesystem. Use an array for `dir` if serving from multiple locations or with different prefixes.
Be mindful of the `maxAge` setting. If you need consistent caching behavior across environments or require different caching in production, explicitly set `config.static.maxAge` in `config/config.default.js` or environment-specific configuration files (e.g., `config/config.prod.js`).
Upgrade your Node.js installation to version `18.19.0` or newer. Alternatively, downgrade `egg-static` to a `2.x` version (e.g., `npm install egg-static@2`) if a Node.js upgrade is not feasible.
Double-check the `config.static.dir` to ensure it points to the correct filesystem path where `my-file.js` resides. Also, confirm that `config.static.prefix` matches the `/public/` part of the URL. Ensure the file actually exists in the specified directory.
After deploying new static assets to a production Egg.js application, ensure you restart the Node.js process (e.g., `npm stop` then `npm start` or via your PM2/Kubernetes deployment strategy) to clear the in-memory cache and serve the updated files.