Skip to content

Commit f6ac285

Browse files
committed
Ensure fastify-express does not interface w/fastify handlers.
1 parent 3c2f387 commit f6ac285

File tree

2 files changed

+29
-13
lines changed

2 files changed

+29
-13
lines changed

CHANGELOG.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,9 @@
22

33
## 8.5.1 - 2025-10-dd
44

5-
### Changed
6-
- Fix fastify request/reply after fastify-express runs.
5+
### Fixed
6+
- Ensure fastify-express does not interfere with native fastify route
7+
handlers.
78

89
## 8.5.0 - 2025-09-18
910

lib/index.js

Lines changed: 26 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -147,24 +147,39 @@ bedrock.events.on('bedrock.start', async () => {
147147
next();
148148
});
149149

150-
// add express compatibility layer to fastify; this translates the express
151-
// API to fastify's
152-
await fastify.register(fastifyExpress);
150+
// capture express hooks added by `fastify-express` so they can be made
151+
// conditional (based on whether any fastify routes take precedence)
152+
const originalAddHook = fastify.addHook;
153+
const capturedHooks = [];
154+
fastify.addHook = function(...args) {
155+
const [name, fn] = args;
156+
if(name === 'captureHook') {
157+
capturedHooks.push(fn);
158+
return this;
159+
}
160+
return Reflect.apply(originalAddHook, this, args);
161+
};
162+
await fastify.register(fastifyExpress, {expressHook: 'captureHook'});
163+
164+
// now register captured hooks, but only run them when there is no defined
165+
// fastify route, ensuring express only runs as a fallback
166+
for(const fn of capturedHooks) {
167+
fastify.addHook('onRequest', function expressFallback(req, reply, next) {
168+
// only run express as a fallback when no fastify route has been defined
169+
// to handle the request
170+
if(req.routeOptions.url === undefined) {
171+
return Reflect.apply(fn, this, [req, reply, next]);
172+
}
173+
next();
174+
});
175+
}
153176

154177
// if server is native http2, add http2 support to fastify express app,
155178
// otherwise (e.g., `spdy` is used) this is unnecessary
156179
if(isNativeHttp2) {
157180
_addHttp2Support(fastify.express);
158181
}
159182

160-
// ensure `request` and `reply` raw values are restored after express runs
161-
fastify.addHook('onRequest', async (request, reply) => {
162-
const app = request.raw.app;
163-
request.raw = app.request;
164-
reply.raw = app.response;
165-
request.raw.app = reply.raw.app = app;
166-
});
167-
168183
// init
169184
await bedrock.events.emit('bedrock-express.fastify.init', {fastify, app});
170185
await bedrock.events.emit('bedrock-express.init', app);

0 commit comments

Comments
 (0)