{"id":17115,"library":"lws-static","title":"lws-static: Static File Server Middleware","description":"lws-static is a dedicated middleware plugin for the lws (local-web-server) ecosystem, designed to serve static files efficiently. It internally wraps koa-static, leveraging its robust capabilities for features like caching and directory indexing. The package is currently at version 3.1.1, actively maintained with periodic updates to its underlying dependencies, notably koa-static, and to ensure compatibility with the lws core framework. Its primary differentiator is seamless integration with lws's configuration system, allowing static file serving to be configured via concise CLI arguments or a programmatic lws setup. This approach simplifies the creation of development servers by offering a unified interface for defining the static root directory, cache control (max-age), request deferral, custom index files, and additional filename extensions, abstracting away direct koa-static configuration for lws users.","status":"active","version":"3.1.1","language":"javascript","source_language":"en","source_url":"https://github.com/lwsjs/static","tags":["javascript","lws","lws-middleware","static","server"],"install":[{"cmd":"npm install lws-static","lang":"bash","label":"npm"},{"cmd":"yarn add lws-static","lang":"bash","label":"yarn"},{"cmd":"pnpm add lws-static","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Provides the core static file serving logic and options.","package":"koa-static","optional":false}],"imports":[{"note":"Since v3.0.0, lws-static is an ESM-only package. The default export is a function that returns the Koa middleware creator.","wrong":"const createStaticMiddleware = require('lws-static');","symbol":"createStaticMiddleware","correct":"import createStaticMiddleware from 'lws-static';"},{"note":"The lws-static middleware is designed to be used with the local-web-server (lws) framework, which is imported separately.","symbol":"Lws","correct":"import Lws from 'local-web-server';"},{"note":"The `Options` type represents the configuration object passed to the `createStaticMiddleware` function, largely mirroring `koa-static`'s options.","symbol":"StaticMiddlewareOptions","correct":"import type { Options } from 'lws-static';"}],"quickstart":{"code":"import Lws from 'local-web-server';\nimport createStaticMiddleware from 'lws-static';\nimport path from 'path';\nimport fs from 'fs';\n\n// Create a temporary directory and file for demonstration\nconst tempDir = path.join(process.cwd(), 'lws-public-temp');\nconst tempFile = path.join(tempDir, 'index.html');\n\n// Ensure the directory exists and contains an index file\nfs.mkdirSync(tempDir, { recursive: true });\nfs.writeFileSync(tempFile, '<h1>Hello from lws-static!</h1>', 'utf8');\n\nconst lws = new Lws({\n  port: 8080,\n  stack: [\n    createStaticMiddleware({\n      directory: tempDir, // Serve from the temporary 'lws-public-temp' directory\n      maxAge: 3600, // Cache for 1 hour (in seconds)\n      index: 'index.html', // Default file if a directory is requested\n      defer: true // Allow other downstream middleware to respond first\n    })\n  ]\n});\n\nlws.start();\nconsole.log(`lws-static server running on http://localhost:8080`);\nconsole.log(`Serving files from: ${tempDir}`);\nconsole.log('Access http://localhost:8080 to see the static content.');\nconsole.log('Press Ctrl+C to stop the server and clean up.');\n\n// Clean up on exit\nprocess.on('SIGINT', () => {\n  console.log('\\nStopping server and cleaning up...');\n  lws.server.close(() => {\n    if (fs.existsSync(tempDir)) {\n      fs.rmSync(tempDir, { recursive: true, force: true });\n      console.log('Temporary directory cleaned up.');\n    }\n    process.exit(0);\n  });\n});","lang":"typescript","description":"Demonstrates programmatic setup of `lws` with `lws-static` to serve static files from a temporary directory. It configures caching, an index file, and proper cleanup."},"warnings":[{"fix":"Migrate your project to use ES modules (`import` statements) or pin `lws-static` to a version prior to 3.0.0 if CommonJS is strictly required for your project.","message":"`lws-static` versions 3.0.0 and above are ESM-only modules. Attempting to use `require()` will result in a runtime `ERR_REQUIRE_ESM` error.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Ensure your Node.js environment is updated to at least v14 and upgrade your `local-web-server` package to version 6.x or newer to ensure compatibility.","message":"The v3.0.0 release of `lws-static` raised its minimum requirements to Node.js v14 or higher and `local-web-server` (lws) v6 or higher, primarily due to the transition to ESM and updated internal dependencies.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Consult the `lws-static` README or `lws --help` for the correct option syntax when using the CLI, and ensure programmatic options are passed as an object to the `createStaticMiddleware()` function.","message":"When configuring `lws-static` via the `lws` command-line interface, all options must be prefixed with `--static.`, e.g., `--static.maxage 3600`. Programmatic usage passes options directly to the middleware factory.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Refer to the official `koa-static` documentation for detailed information on static file serving mechanisms and advanced configuration options.","message":"`lws-static` relies on `koa-static` for its core functionality. While most options are passed through directly, in-depth understanding of `koa-static`'s behavior (e.g., how it handles URL rewriting or directory listings) can be crucial for complex configurations or debugging unexpected behavior.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Update your import statement from `const middleware = require('lws-static');` to `import middleware from 'lws-static';` and ensure your project is configured for ES modules (e.g., using `\"type\": \"module\"` in `package.json` or `.mjs` file extensions).","cause":"`lws-static` v3.0.0 and later are ESM-only modules, and you are attempting to import it using CommonJS `require()` syntax.","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module /path/to/node_modules/lws-static/index.js from /path/to/your/app.js not supported."},{"fix":"Ensure you are using `import createStaticMiddleware from 'lws-static';` and that you are calling `createStaticMiddleware()` as a function when adding it to your `lws` stack, e.g., `stack: [createStaticMiddleware({ directory: './public' })]`.","cause":"This typically occurs if the import path is incorrect, or if the imported symbol is not the default function that creates the middleware (e.g., a named import was used instead of the default export).","error":"TypeError: createStaticMiddleware is not a function"},{"fix":"Double-check the `directory` path for typos or incorrect relative paths. Ensure the directory exists and that your application has the necessary read permissions. Consider using absolute paths with `path.join(__dirname, 'your-static-folder')` for robustness.","cause":"The `directory` option provided to `lws-static` (either via CLI `--directory` or programmatically) points to a path that does not exist on the filesystem.","error":"Error: ENOENT: no such file or directory, stat '/path/to/your/specified-directory'"}],"ecosystem":"npm","meta_description":null}