Nonces, AJAX, script variables & security in WordPress
Alright, so let’s say you develop a website where you enqueue a js script on a page X of your frontend, using:
wp_enqueue_script( 'script_handle', PATH_TO_SCRIPT, array(), '1.0.0', true );
Inside this script, you use a simple AJAX request. You then use the nonce feature of wordpress to have what is stated as a safer AJAX request. And that nonce is passed to the script via:
wp_localize_script( 'script_handle', 'object_name', array( 'nonce' => wp_create_nonce('my-specific-action') ) );
Okay, so far so good.
Now, I’m just wondering in which sense this should make your AJAX request safer. I for example use IIFE in Js to prevent users from using Js functionalities coming with the enqueued script which are not intended for public access. When I however use AJAX requests inside these IIFEs, I need to access the global Js object to access the according nonces. Hence, even if I prevent users from easily using most of the code of my Js via an IIFE, I still need to grab the nonce from within the global scope, which can be easily modified by any frontend user inside the console. Am I wrong? I’m just trying to make my AJAX requests as safe as possible, and avoid unintended requests as far as possible.
What would be the safest way to do so?
wp_localize_script is definitely not the right approach I guess, and I probably think of exclusively using this function to translate strings, as that’s the origin of the name.
Then there’s also
wp_add_inline_script, which allows to add content directly into a specific script, but not into your IIFE in js, for example, so it don’t really see the benefit of using
wp_localize_script, in terms of security. Except if you may code the entire IIFE inside
wp_add_inline_script, but I guess that’s not the purpose.
The thing I often read is that using Js like
var myVar = <?php echo wp_create_nonce("my_nonce"); ?>;
directly inside an IIFE is also subject to injection, which I don’t really understand how (I personally would have chosen this solution as the safest approach, as this allows to generate PHP variables directly inside an IIFE of Js).
So, back to my original question: What’s the best practice used to pass data, not intended for public use, such as AJAX nonces, to
js, in WordPress? Or even generally?