A Comprehensive Guide to Changing baseUrl in Cypress

As an application testing veteran with over 10+ years of experience spanning thousands of devices, one concept I get asked about a lot when it comes to Cypress is how to change the baseUrl across different test environments.

Being able to dynamically modify the baseUrl is key to properly leveraging Cypress for testing web apps targeting various stages – from local development all the way to production.

In this detailed guide, I‘ll share techniques I‘ve refined over years of using Cypress across a diverse set of testing scenarios to help you master updating baseUrl values appropriately.

What Exactly is baseUrl in Cypress?

Simply put – the baseUrl sets the root domain of the web application under test in Cypress. But why is it important?

I‘ve seen many teams struggle with tests failing in certain environments simply due to not configuring this properly.

Here are 5 key reasons why the baseUrl matters:

  1. Defines origin domain for cy.visit() commands
  2. Enables direct navigation like cy.visit(‘/login‘)
  3. Resolves relative URL redirects correctly
  4. Eliminates test failure risk from hard-coded URLs
  5. Speeds up test runs by preventing extra page reloads

Now that we know why it‘s critical, let‘s examine techniques to change the baseUrl across different testing envionments.

When to Change the Cypress Base URL

Before diving into code, it‘s worthwhile knowing when you‘ll need to modify the baseUrl in practical situations:

Scenario Details
Local Dev Testing BaseUrl required to refer dev server domain
Cross Browser Testing Testing on CI cloud platforms requires config per browser
Testing Multiple Environments Targeting stage vs production requires different baseUrl values
Application Domain Changes App domain changes means updating baseUrl config

I‘ve used the methods below to dynamically change the baseUrl across each of these use cases successfully over years of leveraging Cypress.

Setting and Overriding Base URL in Cypress

Cypress offers multiple ways to configure the baseUrl that best suits your testing environment:

1. Via cypress.json

{
  "baseUrl": "http://localhost:8888"
}

2. Inside test code

Cypress.config({
  baseUrl: ‘http://dev.mycorp.com‘
})

3. Through environment variables

APP_BASE_URL="http://app.test.com" npx cypress run 

4. Via command line

cypress run --config baseUrl=http://myapp.stage

I recommend centralizing the value in cypress.json during initial test creation. But leverage overrides via environment variables or command line when executing tests across different runtimes.

Now let me walk through some practical examples I‘ve implemented for readers like yourself facing common dynamic baseUrl scenarios.

Real-World Examples of Changing Base URL

Let‘s say we have a web application MyApp deployed across multiple domains:

And our core site pages are:

  • Home page – /
  • Login – /login
  • User Dashboard – /dashboard

Here‘s how I would handle changing the baseUrl in Cypress tests for MyApp:

1. Cross Environment Testing

Goal: Run same tests across dev, stage and prod

// cypress.config.js

const dev = ‘http://dev.myapp.com‘; 
const stage = ‘http://stage.myapp.com‘;
const prod = ‘https://myapp.com‘;

const config = {
  baseUrl: dev // default is dev  
}

export default config;

Test file:

// Login test
it(‘should login user‘, () => {

  cy.visit(‘/login‘); 

  cy.get(‘#email‘).type(‘[email protected]‘); 
  cy.get(‘#password‘).type(‘t3stpass‘);
  cy.get(‘.login-btn‘).click(); 

  // Assertions
});

Run against different targets:

## Dev Server
npx cypress run  

## Staging 
npx cypress run --config baseUrl=http://stage.myapp.com

## Production
npx cypress run --config baseUrl=https://myapp.com

2. Cross Browser Testing

Goal: Run tests across Chrome and Firefox

// cypress.config.js

const browsers = {
  chrome: ‘http://localhost:3000‘, 
  firefox: ‘http://firefox.myapp.com‘ 
};

const config = {
  baseUrl: browsers[‘chrome‘]
};

export default config;

Test invocation:

### Chrome
npx cypress run

### Firefox
npx cypress run --config baseUrl=http://firefox.myapp.com  

3. Dynamic URL Selection

Goal: Select target baseUrl at runtime

// Get baseUrl from environment variable
const getBaseUrl = () => Cypress.env(‘APP_URL‘);

describe(‘Dynamic App‘, () => {

  beforeEach(() => {
    cy.visit(getBaseUrl()); 
  })

  // Test cases ..
})

Run command:

APP_URL=http://dev.myapp.com npx cypress run

This enables complete flexibility in the baseUrl value without updating config files.

Key Benefits of Configuring Base URL

Setting up the baseUrl properly provides these tangible benefits:

Faster test runs: BaseUrl avoids unnecessary app reloads before executing the actual test logic. This speeds up overall test execution.

Code maintainability: Tests use relative URLs instead of hard-coded full ones scattered everywhere. Changing origin domain requires minimal code changes.

Cross environment stability: No need to modify hundreds of test files when switching between staging vs production.

According to a 2022 survey by Testim.io, teams spend 21% of overall dev time just fixing test suites when environment domains change. Having baseUrl configured saves this wasted overheard in maintaining your tests.

Best Practices for Changing Base URL

Through years of configuring baseUrl values, I‘ve compiled a set of handy best practices:

Centralize baseUrl globally: Define it in one place like cypress.json instead of individual test files

Override dynamically if required: Leverage test config, env vars, CLI params to override baseUrl on demand

Reference using aliases: Use aliases like dev, test instead of raw URLs everywhere

Make baseUrl selection dynamic: Implement runtime functions to chose right baseUrl value

Isolate environment details: Keep environment URLs, domains abstracted out of test code

By following these patterns, you can easily run the exact same Cypress test suite across multiple stages without any code changes!

Avoiding Page Reloads Using BaseUrl

One hidden advantage I want to call out is how baseUrl avoids unnecessary Cypress test runner page reloads.

When you run Cypress locally, it initially opens a blank page before loading your app URL once a test file is executed.

Without baseUrl configured, this sequence happens on every test run:

  1. Cypress test runner page opens on random blank URL
  2. Test file starts execution
  3. First cy.visit() triggers FULL page reload to application root URL
  4. Test logic runs opening more pages

By setting the baseUrl upfront tied to your web app origin, Cypress will avoid Step #3 which eliminates an unwanted full page reload cycle.

Here is a practical example:

// Skipping baseUrl causes this extra reload
cy.visit(‘http://dev.myapp.com‘) 

cy.getCookies() // Actual test logic

With baseUrl:

cypress.json:

{
  "baseUrl": "http://dev.myapp.com"  
}

Test file:

cy.visit(‘/‘) // No unnecessary reload  

cy.getCookies() // Faster execution  

This leads to a much faster first paint especially on heavier apps avoiding the pointless application reload.

As applications grow in complexity, eliminating this one wasteful step pays significant dividends in test efficiency over the long run.

Wrapping Up

The baseUrl forms a fundamental piece of configuring Cypress for both stability and performance during testing. This guide provided techniques I‘ve refined over years of leveraging Cypress to help adjust baseUrl values appropriately.

The key highlights covered were:

✅ Understanding why baseUrl matters
✅ Typical scenarios requiring baseUrl changes
✅ Multiple ways to set and override baseUrl
✅ Practical examples targeting different envionments
✅ How to avoid Cypress reload delays using baseUrl
✅ Best practices for maintaining test resilience

As a final recommendation – always centralize baseUrl for your application globally first, then utilize overrides only when running Cypress across various runtimes.

Following the patterns here will help better optimize stability, execution speed and overall maintenance of your test automation framework.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.