graphiql icon indicating copy to clipboard operation
graphiql copied to clipboard

Add defaultHeaders configuration option

Open marceloverdijk opened this issue 2 years ago • 3 comments

The GraphiQL configuration options already have:

  /**
   * Optionally provide the query in a controlled-component manner. This will override the user state.
   *
   * If you just want to provide a different initial query, use `defaultQuery`
   */
  query?: string;

  /**
   * provide a json string that controls the headers editor state
   */
  headers?: string;

  /**
   * The defaultQuery present when the editor is first loaded
   * and the user has no local query editing state
   * @default "A really long graphql # comment that welcomes you to GraphiQL"
   */
  defaultQuery?: string;

It would be nice to add a defaultHeaders?: string option.

It could e.g be set to: { "X-API-Key": "<ENTER YOUR API KEY>" } to more easier help people fill in their API key.

    ReactDOM.render(
        React.createElement(GraphiQL, {
            fetcher: gqlFetcher,
            defaultVariableEditorOpen: true,
            headerEditorEnabled: true,
            shouldPersistHeaders: true,
            defaultHeaders: '{ "X-API-Key": "<ENTER YOUR API KEY>" }'
        }),
        document.getElementById('graphiql'),
    );

marceloverdijk avatar Jan 17 '22 08:01 marceloverdijk

We currently pass headers, which is populated. And if I refresh the page after changing the default headers (and shouldPersistHeaders is true) that tab keeps the new headers, and a new tab is automatically created with the headers passed as headers. However, if I manually press the + to create a new tab, headers is empty.

Is that this same issue, or should I open up a separate bug report?

(this is using 2.0.2)

SimenB avatar Aug 29 '22 10:08 SimenB

@SimenB the behavior that you describe is actually expected. During the initial render, GraphiQL checks the latest state for tabs persisted in localStorage and compares it with the "controlled props" for editor values (query, variables and headers). If no tab exist that matches these props, then a new one is added.

These controlled props are not designed for defining initial editor values, changing these props "on runtime" would for example also override the editor contents with the new value of the prop. If sounds to me that what you would like to have is exactly the defaultHeaders prop that is described in this issue.

thomasheyenbrock avatar Aug 29 '22 11:08 thomasheyenbrock

Great, thanks for clarifying 👍

SimenB avatar Aug 29 '22 11:08 SimenB

This was just added in #2886, enjoy!

acao avatar Nov 12 '22 16:11 acao