How to deal with license keys in JS

Hi, how should I use a license key in JS? I mean, Should I put it in the js file explicitly?

lightGallery(document.getElementById('gallery'), {
   licenseKey: '',

Or I could define a variable in the vault file and use with de data interface in HTML element, for example. What is de good practice here?


I normally pass these variables along with app.js with wp_localize_script or acorn’s localize function:

add_action('wp_enqueue_scripts', function () {
	bundle('app')->enqueue()->localize('licenseKey', env(‘YOUR_LICENSE_KEY’));
}, 100);

Then in js it’s available on the window object:


I like @Twansparant’s solution. It makes sense to think of a license key as a sort of dependency of your script, and using the localize functions communicates that relationship.

1 Like

Just a reminder. Localize have to pass an array, otherwise it throw an error in latests WP releases.

add_action('wp_enqueue_scripts', function () {
	bundle('app')->enqueue()->localize('jsData', [
        'lg_key' => env('LIGHTGALLERY_KEY')
}, 100);

Ah yes good one!
I always pass all vars in an wp or theme array, this was just as an example but indeed it should be an array, also to avoid conflicts with existing vars on the window object

1 Like