{"id":17754,"library":"koa-reload-middleware","title":"Koa Hot Reload Middleware","description":"koa-reload-middleware is a utility for Koa applications designed to facilitate development by automatically reloading specific middleware modules upon file changes, without requiring a full server restart. This package is currently at version 1.0.1 and, based on its GitHub activity, appears to be in a maintenance state, stable for its specific use case but not under active, rapid development. Its key differentiator is its focused approach to hot-reloading individual Koa middleware, leveraging Node.js's dynamic `import()` for ESM modules. This is particularly useful for avoiding the overhead of tools like `nodemon` for situations where only specific parts of the server-side logic need to be reloaded. It primarily benefits development workflows by significantly reducing feedback loop times when iterating on API routes or other modular Koa middleware components.","status":"maintenance","version":"1.0.1","language":"javascript","source_language":"en","source_url":"https://github.com/jameslnewell/koa-reload-middleware","tags":["javascript","typescript"],"install":[{"cmd":"npm install koa-reload-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add koa-reload-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-reload-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency, as it provides the core application framework for which this middleware is built.","package":"koa","optional":false},{"reason":"Runtime dependency for efficient and reliable cross-platform file system watching to detect changes in middleware files.","package":"chokidar","optional":false}],"imports":[{"note":"The `reload` function is the default export. Requires ESM context for dynamic `import()` within the middleware factory. CommonJS `require` won't work with the provided usage pattern (which relies on `import('./route')`).","wrong":"const reload = require('koa-reload-middleware');","symbol":"reload","correct":"import reload from 'koa-reload-middleware';"},{"note":"While `koa` itself supports both CJS and ESM, the `koa-reload-middleware` example uses ESM. For a consistent setup, use ESM imports.","wrong":"const Koa = require('koa');","symbol":"Koa","correct":"import Koa from 'koa';"},{"note":"When writing Koa middleware in TypeScript, import `Context` and `Next` types for proper type checking and autocompletion.","symbol":"Context, Next","correct":"import type { Context, Next } from 'koa';"}],"quickstart":{"code":"import Koa from 'koa';\nimport reload from 'koa-reload-middleware';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\n// Dummy route file to be reloaded\n// Save this as `routes/my-route.ts`\n// --------------------------------\n// import type { Context, Next } from 'koa';\n// export default async (ctx: Context, next: Next) => {\n//   const message = `Hello from reloaded route at ${new Date().toLocaleTimeString()}`;\n//   ctx.body = message;\n//   console.log(`[ROUTE] Served: ${message}`);\n//   await next();\n// };\n// --------------------------------\n\nconst app = new Koa();\nconst PORT = process.env.PORT ?? 3000;\n\n// The path to the middleware file to be reloaded\nconst middlewarePath = path.resolve(__dirname, 'routes', 'my-route.ts');\n\n// Use the reload middleware. It takes a function that dynamically imports the target middleware.\n// The dynamic import path must be relative to the caller or an absolute file URL.\napp.use(reload(() => import(middlewarePath.replace(/\\\\/g, '/') + `?update=${Date.now()}`)));\n\n// Fallback/catch-all middleware (optional)\napp.use(async (ctx, next) => {\n  if (!ctx.body) {\n    ctx.body = 'Welcome to Koa! Route not matched or reloaded.';\n  }\n  await next();\n});\n\napp.listen(PORT, () => {\n  console.log(`Koa server listening on http://localhost:${PORT}`);\n  console.log(`Edit '${middlewarePath}' and refresh your browser to see changes.`);\n});","lang":"typescript","description":"This quickstart demonstrates setting up a basic Koa server that uses `koa-reload-middleware` to hot-reload a route file. It shows how to define a dynamic import for the middleware and provides a simple dummy route file that can be modified to observe the live reloading functionality without server restarts. The `?update=${Date.now()}` cache-busting query parameter is added to ensure Node.js's module cache is properly bypassed on reloads, which is often crucial for dynamic imports in development."},"warnings":[{"fix":"Ensure `koa-reload-middleware` is only included in development dependencies and is not bundled or enabled in production builds. Use environment variables (e.g., `process.env.NODE_ENV !== 'production'`) to conditionally apply it.","message":"This middleware is designed for development environments only. Using it in production can lead to unexpected behavior, performance overhead, or security vulnerabilities due to dynamic module loading and file system watching.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Configure your project as an ESM module by adding `\"type\": \"module\"` to your `package.json`. If using TypeScript, ensure your `tsconfig.json` has `\"module\": \"NodeNext\"` or `\"ESNext\"` and `\"target\": \"ES2022\"` or higher to support top-level `await` and dynamic `import()`.","message":"The primary usage pattern relies on Node.js's dynamic `import()` statement, which means your Koa application must be configured as an ESM module (`\"type\": \"module\"` in `package.json`) or run with `--experimental-modules` flag (less common now).","severity":"breaking","affected_versions":">=1.0.0"},{"fix":"Modify your `reload` factory function to include a unique query parameter with the dynamic import: `reload(() => import( './my-route.js?update=' + Date.now()))`. This ensures Node.js treats each import as a new module.","message":"Dynamic `import()` in Node.js caches modules. To ensure a fresh load on every change, it's often necessary to add a cache-busting query parameter (e.g., `?update=${Date.now()}`) to the import path, especially for `.js` files without specific handling by `koa-reload-middleware` itself. While `koa-reload-middleware` intends to clear the cache, explicit cache busting is a robust fallback.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Structure your development code such that the dynamically imported module is a single entry point for its logic, minimizing external `import`s that are not themselves dynamically imported. For complex scenarios, consider more comprehensive HMR solutions if this middleware's scope is too limited.","message":"The middleware only reloads the specific module passed to `reload()`. If your reloaded middleware has its own nested dependencies that also change, those nested dependencies might not be reloaded unless `koa-reload-middleware` explicitly clears their cache or they are also dynamically imported within the reloaded module's factory function.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Add `\"type\": \"module\"` to your `package.json` file. Ensure your Node.js version supports ESM without flags (Node.js 14+). If using TypeScript, configure `tsconfig.json` with `\"module\": \"NodeNext\"` or `\"ESNext\"`.","cause":"Attempting to use `import` syntax in a CommonJS module or a Node.js environment not configured for ESM.","error":"SyntaxError: Cannot use import statement outside a module"},{"fix":"Double-check the `middlewarePath` variable. Use `path.resolve(__dirname, 'your', 'route', 'file.ts')` for absolute paths and ensure the file exists. Remember that dynamic `import()` requires full file extensions in ESM.","cause":"The path provided to the dynamic `import()` within `reload()` is incorrect, relative to the wrong base, or points to a non-existent file.","error":"Error: Cannot find module 'path/to/your-route' or TypeError: Path must be a string. Received undefined"},{"fix":"Ensure you are using `import reload from 'koa-reload-middleware';` for ESM. If strictly using CommonJS, `const { default: reload } = require('koa-reload-middleware');` *might* work but isn't the intended pattern, as the internal dynamic import won't work correctly.","cause":"Incorrect import of the `reload` function, likely trying to `require()` it as a default export in a CJS context or destructuring a non-existent named export.","error":"TypeError: reload is not a function"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}