There is not such option to the fastify.register method, but you can do it playing with encapsulation.
You can create a dedicated context that includes your routes + the hook.
This context will be isolated by other context you will create with register.
This example show you how:
const fastify = require('fastify')({ logger: false, exposeHeadRoutes: false })
async function run() {
const route = function routesPlugin(fastify, options, next) {
fastify.get('/hello', async (request, reply) => {
console.log('request')
return { hello: 'world' }
})
next()
}
fastify.register(function intermediatePlugin(instance, opts, next) {
instance.addHook('preValidation', function hook(request, reply, done) {
console.log('only for v1')
done()
})
instance.register(route, { prefix: `/v1` })
next()
})
fastify.register(route, { prefix: `/v2` })
await fastify.inject('/v1/hello')
await fastify.inject('/v2/hello')
}
run()
You can visualize this structure by using fastify-overview (and the fastify-overview-ui plugin together:

Note that the hook is child of the intermediatePlugin that is not shared by the v2's routesPlugin sibling.