DEV Community

Cover image for Automating Authentication in Apollo Sandbox Explorer with Pre-request Scripts
Toan Huynh
Toan Huynh

Posted on

Automating Authentication in Apollo Sandbox Explorer with Pre-request Scripts

Introduction

Apollo Sandbox provides a powerful feature that allows developers to add JavaScript-based scripts to enhance the functionality of their GraphQL requests. These scripts come in two flavors:

  1. Preflight scripts: Execute before every operation, making them ideal for managing authentication flows (e.g., refreshing expired access tokens).
  2. Postflight scripts: Run after the operation completes, useful for validating workflows that depend on response data.

Execution Order of Scripts

Adding a Preflight Script

Follow these steps to add a preflight script that automatically refreshes your access token:

  1. Open Apollo Sandbox and nagivate to the Explorer tab in the sidebar.
  2. Access the Explorer’s Setting.
  3. In the Preflight Script section, click Add script button. A script editor dialog will appears. Sidebar
  4. Enter your JavaScript code in the Script Editor panel. An example script that refreshes an access token is here. Preflight Script Editor
  5. Click Save to store your script. You can use the Test Script button to debug its execution.
  6. Scroll down to the Scripts section in Explorer's Settings to verify that the Preflight script is turned ON. Preflight scripts Config

Using Environment Variables in Headers

To use access token in requests:

  1. Go to the Headers tab in Explorer.
  2. Add an authorization header and set its value using the environment variable syntax: {{accessToken}}.

Your header should look like this:

Explorer Header

Conclusion

By implementing preflight scripts in Apollo Sandbox Explorer, you can:

  • Automate token refresh, eliminating the need for manual re-authentication when access tokens expire.
  • Streamline your development process by automating common tasks and setting variables dynamically.
  • Enhance the efficiency and security of your GraphQL API testing workflow.

Preflight scripts are a powerful tool that can significantly improve your experience when working with Apollo Sandbox Explorer. Give it a try and see how it can benefit your development process!

Reference

Top comments (0)