How to change Cypress baseURL in test?
On This Page What is baseURL in Cypress?January 28, 2026 · 10 min read · Tool Comparison
- What is baseURL in Cypress?
- Reasons to change the base URL in Cypress tests
- Get Started with Cypress change baseURL in test
- Setting the baseURL Dynamically in Cypress Test Configuration
- Other Ways to Set Up Base URL in Cypress
- Examples of changing the substructure URL in Cypress tests
- How to Make Assertions with baseUrl?
- Better Practices for using different bag URLs in Cypress tests
- Example for adding baseURL while running on BrowserStack
- Useful Resources for Cypress
How to change Cypress baseURL in test?
When working with Cypress for end-to-end testing, sustain flexibility and scalability in your test setup is important.
One of the key configurations that helps with flexibility is the baseURL scope, which defines the root URL for your tests. Instead of hardcoding URLs in every test file, set or vary the baseURL dynamically.
Read this usher to con more about the baseURL in Cypress, how to use it, and better practices to be followed.
What is baseURL in Cypress?
The baseUrl is a critical configuration setting that specifies the root URL of your coating. It serves as the base for all cy.visit () calls in your tests.
Cypress mechanisation enable you to specify a baseUrl when configure your test suite. This baseURL acts as the root URL for each visit bid you fulfil in the test suite. As a better pattern, Cypress propose utilize the baseUrl setting.
Defining a baseUrl in your Cypress configuration file enables you to use relative URLs in your tests, get them more decipherable and maintainable.
Read more:
Reasons to change the base URL in Cypress examination
- While publish tests, you choose to run them firstly in a local scene. There are just a few reasons for this. You receive to add the data-cy, check it, and run the tests.
- Prior to execute trial in a test/staging surroundings, you must ensure that local/development surroundings conditions are suitable for screen.
- You might likewise need to configure the CI pipeline so that it can execute in assorted environments. In such example, the baseUrl will be distinct between the two surround. However, in cypress.json, baseUrl can only be configured once.
- The will open localhost or baseURL on a random porthole when it firstly launches. It will switch to the requested URL upon your first request. Without a global baseUrl provided, starting tests will ensue in an unnecessary reload.
- Using a baseURL has the added welfare of grant Cypress to try the url when the test begins and apprise you right away if the application isn & # 8217; t accessible for screen.
- Once the baseURL has be established for the test suite, any subsequent visits to the application under test can be made via comparative links. As the baseUrl can be change during startup configuration, you can target various environments without having to make a lot of environment-specific link settings.
- The baseURL is utilise to set the relative address in the event that your application returns a relative redirect that results in the gap of a new URL. If the baseUrl is present, then this is true. The terminal page visited is utilized if it is not set.
- Between examination, Cypress clears localStorage and cookie, but not session entrepot. You would need to clear it as part of your apparatus if your application expend session entrepot and you need to clear it for a test. When the window is opened. The baseUrl, which serves as the origin of the current window, is affected by sessionStorage.clear ().
Get Started with Cypress alteration baseURL in test
From the projection beginning, you can now admission Cypress in one of the undermentioned style:
npx usage
Keep in mind that npx can be instal independently or as part of npm & gt; v5.2.
npx cypress open
or by using narration
yarn run cypress open
The long route that follows the full path:
./node_modules/.bin/cypress open
Alternatively, you can use the npm bin shortcut
$ (npm bin) /cypress open
The Cypress Launchpad will open in a little while.
Adding npm Scripts
While there is nothing wrong with indite the complete path to the Cypress executable each time, bestow Cypress commands to the scripts field in your package.json is considerably simpler and more graspable.
{'' scripts '': {'' cypress: open '': `` cypress unfastened ''}}You may now run the dictation from the project root as present hither:
npm run cypress: open
Cypress will open up for you right out.
CLI tools
You may also access a large number of other CLI tools by establish Cypress via npm. Plus, you may import Cypress, a properly baked JavaScript library, into your Node scripts.
The Launchpad will scaffold out a set of configuration files befit for your take testing type, and you will be given a list of the modifications to examine.
How to Pass baseUrl through CLI?
Here are the steps to be postdate for surpass baseURL through CLI:
Step 1: Open Terminal in your Project Directory
Move to the radical directory of your Cypress project using the terminal or dictation prompt.
Step 2: Use the & # 8211; config Flag to Override baseUrl
Cypress allows overrule configuration options now through the CLI using the & # 8211; config flag. To set a custom baseUrl, use the undermentioned syntax:
npx cypress run -- config baseUrl=https: //your-custom-url.com
Step 3: Pass baseURL for Specific Test Files
Target specific spec files while passing the baseUrl. For exemplar:
npx cypress run -- spec cypress/e2e/login.cy.js -- config baseUrl=https: //staging.example.com
Step 4: Combine with Former Config Options
The & # 8211; config flag accept a comma-separated list of key-value duet. This means exploiter can modify multiple form values in a single command:
npx cypress run -- config baseUrl=https: //qa.example.com, defaultCommandTimeout=10000
Step 5: Verify baseUrl in Your Tests
If needed, a exploiter can log or assert the current base URL in the tests employ:
cy.log (Cypress.config ('baseUrl '));Read More:
Setting the baseURL Dynamically in Cypress Test Configuration
When using Cypress, the base URL can be given in the configuration file and used dynamically to load the URL.
Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.
To call the set URL dynamically, URLs are set hither and invoked. Add the following line inside env to cypress.config.js.
env: {baseUrl: 'https: //www.programsbuzz.com/user/login ',},The baseURL is given this name in the specification file:
cy.visit (Cypress.env (`` baseUrl ''))
You can do this to take a more dynamical approach:
npx cypress run -- config baseUrl=https: //example.com/
Otherwise, in the package .JSON, you may set a book like to the following:
`` script '': {'' tryout '': `` cypress run '', '' test: staging '': `` cypress run -- config baseUrl=https: //staging-example.com/ '', '' tryout: prod '': `` cypress run -- config baseUrl=https: //prod-example.com/ ''}Then:
npm run test: staging npm run exam: prod
Read More:
Other Ways to Set Up Base URL in Cypress
Apart from using the CLI, Cypress proffer some of the other mutual method to set the baseUrl:
1. Using the cypress.config.js or cypress.config.ts File
This is the about standard way to set a substructure URL, i.e, by defining it forthwith in your Cypress configuration file.
const {defineConfig} = require ('cypress ') module.exports = defineConfig ({e2e: {baseUrl: 'https: //example.com'}})2. Using Environment-Specific Config Files
For teams running tests in multiple environments (like dev, arrange, or production), create tradition configuration files and pass them when lam examination.
npx cypress run -- config-file cypress.config.staging.js
Inside cypress.config.staging.js: module.exports = {e2e: {baseUrl: 'https: //staging.example.com'}}3. Using Environment Variables
Set the baseUrl using environment variables, which is useful for CI/CD pipeline or dynamic frame-up. Cypress supports this via the CYPRESS_baseUrl variable:
CYPRESS_baseUrl=https: //qa.example.com npx cypress run
4. Using Cypress.config () at Runtime (Less Common)
Although not commend for global config changes, users can set the base URL inside a examination or support file use Cypress.config ():
Cypress.config ('baseUrl ', 'https: //dynamic-url.com')5. Using cypress.env.json in Combination with Custom Logic
You can dynamically set the baseUrl in Cypress based on environment variable by combining a cypress.env.json file with custom logic in cypress.config.js:
{'' env '': `` staging '', '' stagingBaseUrl '': `` https: //staging.example.com '', '' prodBaseUrl '': `` https: //www.example.com ''}Then in your cypress.config.js:
const {defineConfig} = require ('cypress ') module.exports = defineConfig ({e2e: {baseUrl: process.env.CYPRESS_env === 'staging'? 'https: //staging.example.com': 'https: //www.example.com'}})Read More:
Examples of changing the groundwork URL in Cypress tests
A wise move is to define a base URL globally in your Cypress configuration file before testing your application with Cypress. This increases test efficiency and makes moving the test suite between assorted environments—like a ontogeny situation and a unrecorded website—less challenging. Here & # 8217; s an instance of that:
// cypress.config.js import {defineConfig} from 'cypress' export default defineConfig ({e2e: {baseUrl: 'http: //localhost:3000'}})You can abbreviate the URLs in your tests by specify the base URL in your configuration file
from
cy.visit ('http: //localhost:3000/index.html ')to
cy.visit ('index.html ')It is elementary to change the base URL from one spot when you are ready to switch to the production site. A farther vantage is that provide a base URL race up Cypress test startup.
Most likely, you & # 8217; ll need to run your tests in several environments:
cy.visit (Cypress.env ('localUrl '))Let & # 8217; s first examine the .visit () education. This command will start a browser at the specified location. But it also habituate the baseUrl property from your cypress.json file.
This implies that if your baseUrl is set to http: //localhost:3000, you may write your URLs like this:
cy.visit ('/dashboard ')and http: //localhost:3000/dashboard will be the resolved localization. The commands .request () and .intercept () also use the baseUrl property. Instead of using an surround variable, do this. You won & # 8217; t have to bother rename everything if you decide one day to alter the gens of your localUrl environment variable.
How to Make Assertions with baseUrl?
Making assertions with baseUrl in Cypress is helpful when you require to verify that your tests are running against the correct environment or to confirm that dynamic routing and navigation are working as require.
Example 1: Assert Current baseUrl
The exemplar given below verifies that the right baseUrl is set in the Cypress configuration:
describe ('Base URL Assertion ', () = & gt; {it ('should have the right baseUrl set ', () = & gt; {expect (Cypress.config ('baseUrl ')) .to.equal ('https: //staging.example.com ')})})Example 2: Use baseUrl in Navigation Assertions
The example shows how to use the configured baseUrl in navigation tests, ensuring the application correctly route to the expect page relative to the environment-specific base URL.
describe ('Navigation Test ', () = & gt; {it ('should navigate to the login page ', () = & gt; {cy.visit ('/login ') cy.url () .should ('eq ', ` $ {Cypress.config ('baseUrl ')} /login `)})})Best Practices for using different base URLs in Cypress trial
Rewriting your cypress.json file and determine baseUrl to a different value each time you wish to switch environment is the best way to accomplish it. It goes without aver that this is irritate and needs way too much work if you need to switch regularly.
Additionally, this is not the greatest strategy if you want to run your tests in uninterrupted integration and use version control. You must charge each time you care to prove in a different environment, which clog up your git story.
Pointing to an alternative configuration file
You can direct Cypress to a different file totally instead of using cypress.json. Assume you have a production.json file with the baseUrl attribute set to the production waiter. You can do the following actions to fulfill Cypress utilize this file:
npx cypress open -- config-file production.json
Naturally, the Cypress run bid likewise functions in this manner.
If you only want to make alteration to the baseUrl attribute, you can do so by passing it through the CLI:
npx cypress open -- baseUrl http: //localhost:3000
Example for adding baseURL while running on BrowserStack
{'' baseUrl '': '' https: //www.browserstack.com/users/sign_up '', '' fileServerFolder '': ``. ``, '' testFiles '': `` * * / * .spec.ts '', '' fixturesFolder '': `` cypress/fixtures '', '' integrationFolder '': `` cypress/integration '', '' pluginsFile '': mistaken, '' supportFile '': false, '' snapshots '': true, '' trashAssetsBeforeRuns '': true, '' reporter '': '' mochawesome '', '' chromeWebSecurity '': mistaken, '' pageLoadTimeout '': 60000, '' reporterOptions '': {'' reportDir '': `` cypress/report/mochawesome-report '', '' reportFilename '': `` testReport '', '' chart '': true, '' overwrite '': false, '' html '': true, '' json '': mistaken, '' timestamp '': `` mm/dd/yyyy_HH: MM: ss ''}}Cypress_local.json
Conclusion
As indicated in the officialCypress documentation, it is not a full idea to forget to set a baseUrl in the Cypress configuration file. This has a few general reward for the puppet & # 8217; s usability, like making it potential to name server problems before lead any tests. But, the major goal is to prevent a second page reload every time Cypress access a URL, which will make Cypress examination run more quickly and without intermission.
You need to for stable testing, and a like BrowserStack for Cypress is a utter picking for this. You can anticipate problems and speak them before your product enters product by having admission to various devices.
Useful Resources for Cypress
Understanding Cypress
Use Cases
Tool Comparisons
On This Page
- What is baseURL in Cypress?
- Reasons to change the groundwork URL in Cypress examination
- Get Started with Cypress change baseURL in test
- Setting the baseURL Dynamically in Cypress Test Configuration
- Early Ways to Set Up Base URL in Cypress
- Examples of change the base URL in Cypress tests
- How to Make Assertions with baseUrl?
- Best Practices for using different base URLs in Cypress examination
- Example for adding baseURL while run on BrowserStack
- Useful Resources for Cypress
# Ask-and-Contributeabout this topic with our Discord community.
Related Guides
Automate This With SUSA
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.
Try SUSA FreeTest Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free