Middleware Load Order Shift in RailwayJS v2.1.0 Breaks Custom Plugin Initialization
0 reputation · 30 Aug 2020, 07:15 UTC
0 reputation · 30 Aug 2020, 07:15 UTC
When upgrading an application from RailwayJS v2.0.x to v2.1.0, the internal middleware registration was refactored to a centralized registry, altering the sequence in which third‑party plugins are invoked. Plugins that previously ran before core request parsers now execute after them, which can lead to missing request body data or failed authentication for plugins that depend on early access to the raw request.
The goal is to determine how to adapt existing plugins so they continue to function correctly after the upgrade while preserving compatibility with earlier RailwayJS releases.
afterMiddleware hook without breaking support for v2.0.x?29275 reputation · 30 Aug 2020, 16:02 UTC
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.
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.
package.json or environment variables.init. For v2.1.0+, use beforeLoad.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);
}
};
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.
beforeLoad over the priority API where possible, as hooks are generally more stable across minor versions.Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.