Rayrun

How do I automatically include an access_token in extraHTTPHeaders using Playwright's API?

Answer

Automatically Including an Access Token in extraHTTPHeaders

To include an access_token in extraHTTPHeaders using @playwright/test, you can create a custom fixture that modifies network requests with extra headers. This fixture should be declared as a dependency for all your testing projects so that it runs before any tests are executed.

Here's a step-by-step guide on how to achieve this:

  1. Create a custom fixture: Write a custom fixture that retrieves the access token and sets it as a header in each HTTP request made during your test suite execution. Use Playwright's API for modifying network requests.
import { test, expect } from '@playwright/test';

test.extend({
  authenticatedContext: async ({ context }, use) => {
    const accessToken = await getAccessToken(); // Replace with your method to get the access token
    await context.route('**/*', (route, request) => {
      route.continue({
        headers: {
          ...request.headers(),
          Authorization: `Bearer ${accessToken}`,
        },
      });
    });
    await use(context);
  },
});
  1. Declare the custom fixture as a dependency: In your test projects, declare the custom fixture as a dependency to ensure it runs before any tests are executed.
import { test } from '@playwright/test';

test('Example test using access token', async ({ authenticatedContext }) => {
  const page = await authenticatedContext.newPage();
  await page.goto('https://ray.run/');
  // Your test logic here
});

By following these steps, you can automatically include an access_token in extraHTTPHeaders for all your test projects using @playwright/test.

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].