Search code examples
javascriptexportglobal-variables

JavaScript prevent changing exported object


Is there any way to prevent exported object to be changed later when it's imported ? I have my config.js helper that manages my config, and I want to export config but I want to only allow changes inside that config.js

let config = null

const refreshConfig = async () => {
  config = {something: "newvalue"}
}

export {config, refreshConfig}

but this way, I am allowed to change it somewhere else like:

import {config} from 'config.js'

config.something = "changing it now"

how to prevent that scenario ?


Solution

  • You have a few options:

    1. If you don't need to change the config object's property values within the module, freeze it when loading it:

      config = Object.freeze({something: "new value"});
      

      You can still replace it (inside the module), you just can't change property values on it.

    2. Export a proxy that only allows allows retrieving information, not updating it.

      let realConfig = null;
      
      const config = new Proxy({}, {
          get(target, propName) {
              return realConfig && realConfig[propName];
          }
      });
      

      (You might choose to implement more proxy traps than just get.)

    3. Export a function that allows the caller to receive a defensive copy of the config, not the actual config.

    #1 seems most applicable to the code in the question.