Welcome to the Linux Foundation Forum!

Why do you use Object.assign?

I want to know why is good practice using assign, in that case, seems to me you want to clone opts, but I do not understand why not use only opts.

It's essentially shallow merging the options passed to the app.js plugin function with an empty object.


  •   fastify.register(AutoLoad, {
        dir: path.join(__dirname, 'plugins'),
        options: opts   // why not?
      fastify.register(AutoLoad, {
        dir: path.join(__dirname, 'plugins'),
        options: Object.assign({}, opts)
  • This would be a good issue to open on Fastify itself, I don't know why opts isn't passed directly.

    It could be that shallow cloning as a pattern for initializing plugins affords some protection against a certain class of bug that would arise from mutating opts objects at different layers. They could use spread {...opts} for shallow cloning as well, but this code was probably first written prior to spread support in Node.

  • davidmarkclements
    davidmarkclements Posts: 270
    edited January 2022

    I spoke with the lead maintainer of Fastify. It's because Fastify may mutate the opts object (mostly by adding internal tracking symbols), so using Object.assign avoids unexpected mutations of options objects between plugin layers.


Upcoming Training