Description
Prerequisites
- I have written a descriptive issue title
- I have searched existing issues to ensure the bug has not already been reported
Fastify version
5.2.1
Plugin version
6.1.0
Node.js version
20.12.2
Operating system
macOS
Operating system version (i.e. 20.04, 11.3, 10)
14.4 (23E214)
Description
I've encountered an issue when using the dirNameRoutePrefix option together with autoHooks.
When dirNameRoutePrefix is set to false, auto-hooks are applied not only to the parent folder but also to its first-level child routes. Additionally, if dirNameRoutePrefix is a function that selectively returns false for specific folders, only the parent folder’s routes will use the hooks from the folder marked as false.
Example Configurations
- Global false value (Issue)
fastify.register(pluginAutoload, {
...defaultAutoloadOptions,
// ISSUE: The parent folder routes and the first-level child routes
// will inherit the last registered hook (e.g., third.hook.mjs).
dirNameRoutePrefix: false,
})
- Conditional Prefixing (Issue)
fastify.register(pluginAutoload, {
...defaultAutoloadOptions,
dirNameRoutePrefix: (folderParent, folderName) => {
if (folderName === 'third') {
return 'yellow-submarine';
}
// ISSUE: The parent folder routes and the first child routes
// will still inherit the last registered hook (e.g., third.hook.mjs).
return false;
},
})
- More Granular Control (Partial Issue)
fastify.register(pluginAutoload, {
...defaultAutoloadOptions,
dirNameRoutePrefix: function rewrite(folderParent, folderName) {
if (folderName === 'third') {
return 'yellow-submarine'; // This works fine.
}
if (folderName === 'first') {
return false;
// ISSUE: In this case, the parent folder will still use hooks
// from inside this folder.
}
return folderName; // This works fine.
},
})
Additional Notes
In my actual application (which I can't share), I use the second example because I want most routes to have no prefix while only a few specific ones are prefixed. However, in this setup, I've encountered cases where the hook inside a falsy folder is not applied at all. This behavior is inconsistent, and I haven't been able to reproduce it in my test repository.
Link to code that reproduces the bug
https://github.com/MrWook/reproduction-fastify-autoload-hook-issue
Expected Behavior
dirNameRoutePrefix is not interfering with autohooks so that the hooks are still only used in the specific folder