0

I am using wp_localize_script() to add variables from my config.ini file to my inline JS code (inside HTML block element of Elementor) [Please see this for reference]

But this method is unsafe to add Security keys because these variables can be accessed via console. How can I add API security keys to my JS code securely? Is there any way I can achieve this? Thank you in advance.

2

You can't. Any secrets you put into your pages or JavaScript can be read out of the downloaded files by the client.

Instead, you probably want to either:

  1. Move the secrets into your server-side code and have your server code make requests to external APIs using the secrets, and use WordPress nonces and login cookies to authenticate your client scripts to your server
  2. If you're using a third-party service that users can authenticate against directly, set up OAuth or OpenID connect to get your users authenticated against that service. Then, your script can use the tokens returned by that (which are per-user) to request that service.
2
  • I am using js command fetch('https://pixabay.com/api/?key=MY_SECRET_KEY&q='+keyword) to search images for the user for their keyword. I want to save this secret key in my config.ini file so its easier to change it if required, and it's secured and my clients cannot access this key. What is the best way to do it?
    – aditya
    Apr 20 at 17:02
  • 1
    @aditya you can use WP to proxy the request. Your JS -> custom REST endpoint -> external API. This way, you can add the secret in PHP and not leak it
    – kero
    Apr 27 at 12:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.