1

In a simple HTML page, I have some JS like below

<script>

   let users;

   axios.get(url)
   .then((resp) => {
      users = resp.users;
   }) 
    
   // other stuff
</script>

users is now accessible to access in console since it's on the window object. Would wrapping all that logic in an IFFE protect it from being accessible?

<script>

   (function() {
      let users;

      axios.get(url)
      .then((resp) => {
         users = resp.users;
      }) 
      // other stuff
   })();

</script>
RicardoAlvveroa
  • 226
  • 1
  • 8
  • Your code won't work! See [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – FZs Jan 12 '21 at 18:59
  • @FZs that's not what OP is asking about though. please review again – Tibebes. M Jan 12 '21 at 19:00
  • 5
    You can remove it from the global window object, but what else might you mean by "protect"? If you're trying to prevent the user from being able to see that data at all, you can't. – David Jan 12 '21 at 19:01
  • @David right , they can just look at the network call being made and see the response but as far as protecting the variable accessibility I mean. My example was probably bad, but if I had a constant defined that i wanted to be protected, that might be a better example than setting a variable to a network response – RicardoAlvveroa Jan 12 '21 at 19:03
  • @RicardoAlvveroa you don't even know for sure that the user is accessing your site from a web browser; it could be anything. – Pointy Jan 12 '21 at 19:22

1 Answers1

4

Would wrapping all that logic in an IFFE protect it from being accessible?

Only very minimally. Or in modern environments you could add type="module" to the script so that code is executed as a module (the top level scope of modules isn't global scope).

But, this doesn't really do anything to protect the data. Anyone using your site can inspect the Network tab, or set a breakpoint inside your Axios callback, or use a network sniffer, or...

Any data you send the client is shared with the end user, if they want to see it. If you don't want them to see it, don't send it to them.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • thanks TJ....perhaps a bad example on my part using a network call. What about if it wasn't a network call and just a constant I defined? – RicardoAlvveroa Jan 12 '21 at 19:04
  • 3
    It doesn't make any difference where the data is coming from. It's on the user's computer, there's always a way for them to access it. – Guy Incognito Jan 12 '21 at 19:05
  • @RicardoAlvveroa - The constant would be defined in a JavaScript file, which would be delivered to the client...via the network. Just as easy (if not easier) to see it, I'm afraid. If it goes to them at all, they can see it. – T.J. Crowder Jan 12 '21 at 19:21