Skip to content

Including enqueuedScripts field can lead to broken output if scripts are printed in this action #3397

@mboynes

Description

@mboynes

Description

When a query includes the enqueuedScripts or enqueuedStylesheets fields, WPGraphQL fires the wp_enqueue_scripts action. It is not uncommon for plugins to render scripts or styles during this action, e.g. using wp_print_inline_script_tag(). If a plugin were to do this, including one of these fields would break the GraphQL response, as it would include HTML markup alongside the JSON response.

Unfortunately, I recently encountered this on a network of sites after the host auto-updated Jetpack from 14.7 to 14.8. This update included a fairly innocuous change containing exactly what is described above, a call to wp_print_inline_script_tag().

Steps to reproduce

  1. Output some script during the 'wp_enqueue_scripts' action:
    add_action( 'wp_enqueue_scripts', function () {
        wp_print_inline_script_tag( 'window.Whoops = 1;' );
    } );
  2. Make a GraphQL request which includes enqueuedScripts :
    query WhoopsQuery($id: ID!) {
      post(id: $id, idType: DATABASE_ID) {
        enqueuedScripts {
          nodes {
            src
          }
        }
      }
    }
  3. Observe the broken response, e.g.:
    {
      "errors": [
        {
          "message": "Unexpected token '<', \"\t<script>\nw\"... is not valid JSON",
          "stack": "SyntaxError: Unexpected token '<', \"\t<script>\nw\"... is not valid JSON"
        }
      ]
    }

Additional context

I'd recommend adding output buffering around the do_action( 'wp_enqueue_scripts' ); call.

WPGraphQL Version

2.3.3

WordPress Version

6.8.2

PHP Version

8.3.22

Additional environment details

No response

Please confirm that you have searched existing issues in the repo.

  • Yes

Please confirm that you have disabled ALL plugins except for WPGraphQL.

  • Yes
  • My issue is with compatibility with a specific WordPress plugin, and I have listed all my installed plugins (and version info) above.

Metadata

Metadata

Assignees

No one assigned

    Labels

    impact: medMinor performance improvements, fix broad user base issuestype: bugIssue that causes incorrect or unexpected behavior

    Type

    Projects

    Status

    ✅ Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions