middle-router is a universal routing library designed for both client-side and server-side JavaScript applications, allowing URL changes to be processed through a series of asynchronous middleware functions. As of version 2.2.0, it provides a consistent API for managing routing logic across different environments. It distinguishes itself by integrating Koa-style `await next()` patterns for middleware execution, enabling control to flow downstream and then back upstream. This allows for complex lifecycle management around route changes, such as measuring execution time, handling exit conditions, or even prompting before navigation. The library leverages `path-to-regexp` for flexible path matching, similar to Express 4.x, and utilizes `middle-run` for robust middleware orchestration. While the provided examples often showcase integration with frameworks like Express and React, `middle-router` itself is entirely framework-agnostic, offering core routing functionality without imposing external dependencies. It focuses on providing a flexible and powerful middleware-based approach to handling application state changes tied to URLs. Its release cadence is stable, with new features and bug fixes rolled out incrementally.
npm install middle-routerVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to create a `middle-router` instance, define asynchronous middleware functions for different paths, and use `router.route()` to process URLs, simulating both specific and default route handling in a Node.js environment.
Ensure `await exiting` is placed *after* `resolve()` in your middleware. Placing it before `resolve()` will prevent the route from resolving until the next URL change occurs, leading to unexpected behavior and potential hangs.
When upgrading major versions, always review the official API documentation for your specific major version. The expected arguments for middleware functions (`{ context, next, params, resolve, etc. }`) may have undergone significant changes or reordering.For browser-based client-side routing, ensure you explicitly call `router.on('route', handler)` to process the resolved view data and `router.start()` to initiate routing and listen for browser history (e.g., `popstate`) and hash changes.Change your import statement to `import Router from 'middle-router'` to correctly access the default exported constructor.
Ensure all execution paths within your middleware functions either call `resolve(viewData)`, call `await next()` (if passing control to subsequent middleware), or explicitly throw an error to prevent the routing process from hanging indefinitely.
Remember that `middle-router` provides core routing logic. If integrating with React, it supplies the 'view' (e.g., a React element) that you then render with `ReactDOM`, but it does not replace or depend on `react-router-dom`.
No dependency data recorded yet.