Adapting Plugins for the v2.1.0 Middleware Refactor
To maintain plugin functionality after upgrading to RailwayJS v2.1.0 while preserving v2.0.x compatibility, you should move middleware registration to the beforeLoad lifecycle hook or utilize the priority API, wrapped in a version-conditional check.
Explanation and Context
Confirmed Fact: The RailwayJS v2.1.0 release notes document a "Middleware pipeline refactor." This change alters the loader to sort middleware by plugin name before applying the core stack, which shifts the execution sequence.
Likely Explanation: Because the refactor moved global middleware registration to occur after the core routing stack, plugins that register middleware within the standard init hook now execute after body-parsers and routing. This results in plugins failing to access raw request bodies or failing to authenticate requests before they hit the router.
Implementation Steps for Compatibility
- Detect Version: Determine the active RailwayJS version via
package.json or environment variables.
- Conditional Registration: Use a version guard to determine which hook to use. For v2.0.x, continue using
init. For v2.1.0+, use beforeLoad.
- Priority Override: If
beforeLoad is insufficient, use the priority API with a negative value to force early execution.
// plugin.js
const pkg = require('../package.json');
const railwayVersion = pkg.dependencies.railwayjs || process.env.RAILWAYJS_VERSION || '2.0.0';
const isV21OrLater = /^2\.1\./.test(railwayVersion);
function registerMiddleware(app) {
app.use((req, res, next) => {
// Your early-access logic here
next();
});
}
module.exports = {
name: 'my-custom-plugin',
init(app) {
// v2.0.x path: init runs early
if (!isV21OrLater) registerMiddleware(app);
},
beforeLoad(app) {
// v2.1.0+ path: beforeLoad ensures execution before core stack
if (isV21OrLater) registerMiddleware(app);
}
};
Verifying Execution Order
To confirm the shift and verify your fix in a v2.1.0 environment, use the built-in debug logging:
DEBUG=railwayjs:middleware node index.js
Review the startup logs. In a broken v2.1.0 state, core middleware (like bodyParser) will appear before your plugin. After applying the beforeLoad fix, your plugin's middleware should appear at the top of the list.
Recommended Compatibility Pattern
- Prefer Lifecycle Hooks: Use
beforeLoad over the priority API where possible, as hooks are generally more stable across minor versions.
- Avoid Hard-coding: Do not assume a specific index in the middleware array; always rely on the provided hooks or explicit priority values.
- Scoped Testing: Verify the plugin in a staging environment using the exact v2.1.0 release to ensure error handling remains consistent.