☰
WORDPRESS / PRACTICE

Reliable JavaScript Configuration Passing in WordPress

Reliable JavaScript Configuration Passing in WordPress

Errors such as `undefined is not a function`, a missing nonce, or unstable behavior after JavaScript optimization are often caused not by the code itself, but by an incorrect execution order. A script may run before its dependency has loaded or attempt to read configuration that is not yet present on the page.

In WordPress, this problem is addressed with two rules: register dependencies explicitly, and add JavaScript data to a specific script handle through the WordPress API. This approach works more reliably with Gutenberg, WooCommerce, caching, file concatenation, and deferred loading.

Why JavaScript Execution Order Matters in WordPress

Browsers execute JavaScript in a specific sequence. If `checkout.js` uses `wp.apiFetch` but the file that provides this object has not loaded yet, the console will show an error. A similar issue occurs when the main script expects `window.checkoutConfig`, but the variable is declared later or is not output at all.

Optimization tools create additional risks: they may combine files, change how they load, add `defer`, or delay execution. If dependencies and configuration are not described through WordPress mechanisms, optimization can change the order the developer relied on.

  • A dependency loads after the script that uses it.
  • Configuration appears in the global scope accidentally or uses a conflicting name.
  • One handle is registered multiple times with different files or versions.
  • Inline code is added to the page separately and loses its connection with the main script.

Register Dependencies with wp_enqueue_script

In the dependency array, specify the handles of scripts that must be available first. WordPress uses this information to build the loading order. Do not rely on a required file having already been added by the theme or another plugin: this may change after an update or on a different page template.

First, register or enqueue the main file. In the `checkout-app` example, the script depends on `wp-api-fetch`, so WordPress will output API Fetch before the application code.

  • Use a stable, unique handle, such as `my-plugin-checkout`.
  • Specify actual handles, not file names. The handle `api-fetch.js` and the handle `wp-api-fetch` are not the same thing.
  • Provide a script version so the cache can be refreshed correctly after changes.
  • Load the file in the required context: only on pages where it is actually needed.
<?php
wp_enqueue_script(
    'checkout-app',
    plugin_dir_url(__FILE__) . 'assets/checkout.js',
    array('wp-api-fetch'),
    '1.0.0',
    array('in_footer' => true)
);

Pass Configuration with wp_add_inline_script

`wp_add_inline_script()` attaches the added code to a specific handle. When the `before` position is used, the configuration is output before the main file. This is the correct option when `checkout.js` reads the data immediately during execution.

The `before` parameter is important: it means “before the associated script,” not after the PHP function call. If the configuration is needed only after the main file has finished, you can use `after`, but that is often too late for initial settings.

  • Add inline code after registering or enqueueing the handle.
  • Attach the configuration to the exact handle that consumes it.
  • Do not create dozens of independent global variables; use a single namespace.
  • Do not send secret keys, passwords, or private tokens to the browser.
<?php
$config = array(
    'nonce'    => wp_create_nonce('wp_rest'),
    'currency' => function_exists('get_woocommerce_currency')
        ? get_woocommerce_currency()
        : 'USD',
);

wp_add_inline_script(
    'checkout-app',
    'window.checkoutConfig = ' . wp_json_encode($config) . ';',
    'before'
);

Serialize Data Safely with wp_json_encode

Do not insert PHP values into JavaScript through unencoded concatenation. Strings may contain quotation marks, line breaks, special characters, or values that alter the script syntax. `wp_json_encode()` converts a PHP array into valid JSON that the browser can read as a JavaScript object.

Check the contents of the data before passing it. Front-end configuration is available to the page user, so a nonce, REST API URL, currency, product IDs, or public settings are one thing, while a secret API key is something entirely different.

  • Build the configuration as a PHP array rather than as a ready-made JavaScript string.
  • Check functions and plugin dependencies if the code may run without WooCommerce.
  • Do not use `esc_js()` as a replacement for JSON serialization of an array.
  • For nested structures, also pass the array to `wp_json_encode()`; it will preserve nested objects and lists.
<?php
$config = array(
    'restUrl'  => esc_url_raw(rest_url('my-plugin/v1/')), 
    'currency' => 'UAH',
    'features' => array(
        'guestCheckout' => true,
        'coupons'       => false,
    ),
);

wp_add_inline_script(
    'checkout-app',
    'window.MyPlugin = window.MyPlugin || {};'
        . 'window.MyPlugin.checkout = ' . wp_json_encode($config) . ';',
    'before'
);

How to Read Configuration in a JavaScript File

The main file should expect a consistent data structure and should not fail completely if an optional field is missing. Check the object before using it, especially if some pages may load without the required plugin.

A global variable is acceptable for a small configuration, but using a unique namespace is a better approach. This reduces the likelihood of conflicts with a theme, another plugin, or a third-party library.

  • Define a clear structure containing the URL, nonce, currency, and feature flags.
  • Do not change field names without updating both the PHP and JavaScript at the same time.
  • Separate configuration from business logic: pass data inline while keeping behavior in the file.
  • If a nonce is refreshed or becomes invalid, handle the server response and provide a way to obtain a new nonce.
(() => {
    const config = window.MyPlugin?.checkout;

    if (!config) {
        console.error('Конфігурацію checkout не знайдено.');
        return;
    }

    console.log('Валюта:', config.currency);

    // Для REST-запитів використовуйте config.restUrl і config.nonce.
})();

Why wp_localize_script Should Not Be Used for Every Type of Data

`wp_localize_script()` was historically designed to pass translations from PHP to JavaScript. It can create a global object and technically pass arbitrary values, but it is a less clear and expressive approach for general configuration.

For application settings, URLs, feature flags, and other structured data, use `wp_add_inline_script()` together with `wp_json_encode()`. Reserve `wp_localize_script()` for localized strings and related translation data.

  • Do not pass large product arrays or the results of complex queries through `wp_localize_script()`.
  • Do not give the object an overly generic name, such as `config` or `data`.
  • Remember that both localized data and inline configuration still appear in the generated HTML.

Check Load Order and Common Errors

After enqueueing the scripts, open the browser DevTools and check more than just whether errors are present: verify the actual order as well. The Network tab shows file loading, Sources or Elements show inline code and `script` tags, and the Console shows errors related to dependencies or configuration.

Test the page with caching disabled, after clearing the optimization tool's cache, and with deferred-loading settings enabled. An optimization tool may change behavior even when the order is correctly defined in the original PHP.

  • Make sure `wp-api-fetch` or another required dependency is actually present on the page.
  • Find the inline configuration in the HTML and verify that it appears before `checkout.js` when `before` is used.
  • Check whether the same handle is output twice with different URLs or versions.
  • Compare authenticated and unauthenticated pages: the nonce and data availability may differ.
  • Temporarily disable JavaScript concatenation and deferred execution to distinguish a code error from an optimization error.

Symptoms and Likely Causes

If you see `checkoutConfig is not defined`, the inline code was not output, was attached to a different handle, or appeared after the main file had already executed. The error `wp.apiFetch is not a function` usually indicates a missing or incorrectly specified dependency.

If everything works without the optimization tool but breaks after it is enabled, check the `defer`, execution delay, concatenation, and exclusion settings for dependent scripts. Do not fix the issue by adding random `setTimeout` calls: this masks the ordering problem instead of resolving it.

Frequently asked questions

Do you always need to use a global variable for configuration?

No, but it is a simple option for a small amount of server-side data. Use a unique namespace, such as `window.MyPlugin.checkout`, and do not store secrets there. For more complex integrations, some data can be retrieved through the REST API.

When should wp_add_inline_script use after?

`after` is suitable for code that must run after the main file, such as initialization or a call to a function declared in that script. If the file reads the configuration during loading, use `before`.

Is a nonce a secret value?

A nonce should not be treated as a password or a complete authentication mechanism. It helps verify a request in the WordPress context, but the server must still check user permissions. Do not pass secret keys together with it.

Why does the code work in a theme but not in Gutenberg or WooCommerce?

Different contexts may have different pages, handles, execution timing, and dependency sets. Check that the script is loaded where it is needed, its dependencies are registered, and the configuration is attached to the correct handle.

Conclusion

Reliable interaction between PHP and JavaScript in WordPress starts with an explicit description of dependencies. Enqueue scripts with `wp_enqueue_script()`, pass configuration with `wp_add_inline_script()`, and serialize it with `wp_json_encode()`.

Then verify the actual HTML, execution order, and behavior with optimization tools enabled. This approach eliminates accidental global variables, reduces `undefined` errors, and makes code more predictable in plugins, themes, Gutenberg, and WooCommerce.

← All WordPress materials