I am currently working on a JavaScript project and know that JavaScript source code is accessible through the browser. In the code, I have a variable that stores a secret string that is used by the program. However, I do not want others to view the source code and find out the value of this variable. Is there a way to hide the value of a variable? Or is it possible to change the variable value after? For instance, change the actual source code to set the variable to a different value? This variable is only used the first time an image is loaded so it would be okay to remove it altogether if that is possible.
You cannot hide JavaScript content from a programmer. They can always open the developer console and get all your variables.
What's worse, they can use said console to directly bypass any JavaScript validation, so it cannot be your primary security.
If it is something you must hide or secure against, you must look into a server side solution.
Javascript is run on the client, so I don't think this is going to possible. Anything that you need to be kept secret is going to need to be server side.
What you ask is impossible at the moment.
But there's a JavaScript proposal Function implementation hiding, which – as the name suggests – hides function implementation from being observed. The proposal originated in mid-2019, and is in stage 2 (out of 4) at the moment. I personally doubt that it will ever be part of the standard, but if it does, in theory you could hide the secret inside of the body of a hidden function:
function fetchData() {
"sensitive"; // ← the proposal
const SECRET = "VGhlIG1lc3NhZ2UgaXM6IFIyeHZjbmtnZEc4Z1ZXdHlZV2x1WmZDZmg3cnduNGVt";
return fetch(DATA_URL, {
headers: {
"Authorization": `Bearer ${SECRET}`,
},
});
}
The SECRET
variable cannot be inspected through debugger or through fetchData.toString()
. However, the value of Authorization
header is visible in a network tab in console, so the whole thing is inappropriate for this use case.
JavaScript is client side, and there isn't really anyway to hide the code.
What you can do: Prevent common users from seeing it (aka making it harder to find)
My suggestion is to encrypt the data using some sort of cipher (preferably not an online encryption tool). This stops most lazy people from seeing it.
(Assuming no one is actually trying to find this mysterious value)
Well, you can just put the entire code into one function and then execute it after that in the same script. That helped me.
© 2022 - 2024 — McMap. All rights reserved.
(function(){ const x = prompt("give me a secret"); ... })()
? – Limenprompt("password")
that should be fairly secure in the most browsers. – Limen