What’s the best way to use waitForURL in Playwright scripts?

I’m automating a web application using Playwright on Windows 10 with Node.js v14.16.0. After submitting a form, the application navigates to a new page.

I tried using waitForURL() to wait for the new page to load, but the behavior is inconsistent. Sometimes it times out, and other times it doesn’t seem to wait properly. I need a reliable way to handle page transitions after navigation.

How should waitForURL() be used correctly to make navigation handling stable and consistent?

The most common mistake with waitForURL() is calling it after the navigation has already started or completed. Like other Playwright wait methods, timing matters.

The most reliable pattern is to combine the action that triggers navigation with waitForURL() using Promise.all():

await Promise.all([
page.waitForURL('https://example.com/new-page
'),
page.click('#submit-button')
]);

This ensures:

Playwright starts waiting before the navigation is triggered.

The navigation cannot be missed due to timing issues.

If your page loads slowly, increase the timeout:

await page.waitForURL('https://example.com/new-page
', { timeout: 10000 }); ```

If your application uses redirects or dynamic URL segments (like IDs or query params), matching the exact URL may fail.

In such cases, use a regular expression:

await Promise.all([
page.waitForURL(//new-page/),
page.click('#submit-button')
]);

This works well when:

URLs contain dynamic parameters (e.g., /new-page?id=123).

Redirects happen before reaching the final page.

The base domain changes between environments (dev, staging, prod).

Using regex makes the wait more flexible and reduces false timeouts.