Im making API request from facebook graph api. i would like to hide the id and access token from client side. so i stored the access token on php then i got the data with js. but then i realized that it still shows on the console.log . how can i make it secure ? how to hide the api key? the data still show on the console so im not sure how i can hide thed data. i also have tried .env method but i know i can access from client side only on server side.
let faceIDnum = sns_show_options.facebookID;
let faceID = faceIDnum.toString();
console.log(faceID);
const businessIDface = faceID ;
this is how i did with js.
require_once __DIR__ . '/vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
$snspostcount = get_option('post_count_number');
$sns_facebook_id_info = get_option('facebook_page_id' );
$sns_post_count = putenv("SNS_POST_TOTAL=$snspostcount");
$sns_post_count_val = getenv('SNS_POST_TOTAL');
$sns_facebook = putenv("SNS_FACEBOOK_ID=$sns_facebook_id_info");
$sns_facebook_id = getenv('SNS_FACEBOOK_ID');
// $nametag = $_ENV["SKDAI"];
var_dump($sns_post_count_val);
function wp_enqueue_javascript_scripts() {
wp_register_script( 'javascript-js', get_template_directory_uri() . './js/index.js', array(), '1.0.0', true );
wp_enqueue_script( 'javascript-js' );
wp_localize_script( 'javascript-js', 'sns_show_options',
[
'facebookID'=> getenv('SNS_FACEBOOK_ID')
]
);
}
My Answer:
To hide the API key from the client-side, you can use PHP to store the API key securely on the server-side and then pass it to JavaScript using AJAX or server-side rendering. Here's an example of how you can achieve this:
1. Store the API key securely in a PHP file on the server:
php
// api_keys.php
$api_key = 'your_api_key_here';
?>
2. Create a PHP file to handle the API request and pass the API key to JavaScript:
php
// api_request.php
require_once 'api_keys.php';
// Make API request using $api_key
// Return API response to JavaScript
echo json_encode($api_response);
?>
3. In your JavaScript file, make an AJAX request to the PHP file to get the API response:
javascript
// index.js
$.ajax({
url: 'api_request.php',
type: 'GET',
success: function(response) {
// Handle API response
console.log(response);
}
});
4. Make sure to include the PHP file in your WordPress theme's functions.php file and enqueue the JavaScript file:
php
// functions.php
function wp_enqueue_javascript_scripts() {
wp_register_script('javascript-js', get_template_directory_uri() . '/js/index.js', array(), '1.0.0', true);
wp_enqueue_script('javascript-js');
}
add_action('wp_enqueue_scripts', 'wp_enqueue_javascript_scripts');
By following this approach, you can securely store and pass the API key from PHP to JavaScript without exposing it to the client-side.
Rate this post
4 of 5 based on 1161 votesComments