---
id: api/commands/visit
title: cy.visit()
description: >-
  Visit a URL in Cypress with cy.visit() to load a page, send headers or auth,
  handle status codes, and run page load callbacks.
section: api
source_path: docs/api/commands/visit.mdx
version: 1934fa485ad0afcbbd3bdb674d5c5f1f991b55cf
updated_at: '2026-11-14T05:15:51.878Z'
---
# visit

Load a URL in the application under test. `cy.visit()` waits for the page to fire its `load` event, then yields the page's `window` object.

We recommend setting a `baseUrl` when using `cy.visit()`. See [Setting a global `baseUrl`](/llm/markdown/app/core-concepts/best-practices.md#Setting-a-Global-baseUrl).

## Syntax

```
cy.visit(url)
cy.visit(url, options)
cy.visit(options)
```

### Usage

**Correct Usage**

```
cy.visit('/') // visits the baseUrl
cy.visit('index.html') // visits a local file when baseUrl is null
cy.visit('http://localhost:3000') // full URL: no baseUrl, or another host
cy.visit({
  url: '/pages/hello.html',
  method: 'GET',
})
```

### Arguments

**url _(String)_**

The URL to visit.

When `baseUrl` is set, Cypress prefixes the URL with it. Without a `baseUrl`, provide a fully qualified URL, or Cypress serves the path as a local file. See [how `cy.visit()` prefixes URLs with `baseUrl`](#How-cyvisit-prefixes-URLs-with-baseUrl).

Visiting a new origin reloads the Cypress window. To visit a different origin in the same test, use [`cy.origin()`](/llm/markdown/api/commands/origin.md), even when the origins share a superdomain (unless [`injectDocumentDomain`](/llm/markdown/app/references/configuration.md#injectDocumentDomain) is enabled).

**options _(Object)_**

Pass in an options object to control the behavior of `cy.visit()`.

| Option | Default | Description |
| --- | --- | --- |
| `url` | `null` | The URL to visit. Cypress appends it to the `baseUrl` if one is configured. Behaves the same as the `url` argument. |
| `method` | `GET` | The HTTP method to use in the visit. Can be `GET` or `POST`. |
| `body` | `null` | An optional body to send with a `POST` request. A string is sent unmodified. An object is URL encoded and sent with a `Content-Type: application/x-www-form-urlencoded` header. |
| `headers` | `{}` | An object that maps HTTP header names to values to send with the request. Cypress sends `headers` only with the initial `cy.visit()` request, not with any later requests. |
| `qs` | `null` | Query parameters to append to the `url` of the request. Must be an object. |
| `log` | `true` | Displays the command in the [Command Log](/llm/markdown/app/core-concepts/open-mode.md#Command-Log). |
| `auth` | `null` | Adds Basic Authorization headers. |
| `failOnStatusCode` | `true` | Whether to fail on response codes other than `2xx` and `3xx`. |
| `onBeforeLoad` | none | Called before your page has loaded all of its resources. |
| `onLoad` | none | Called once your page has fired its load event. |
| `retryOnStatusCodeFailure` | `false` | Whether Cypress retries the request when the status code is outside `2xx` and `3xx`. When `true`, Cypress retries up to 4 times. Requires `failOnStatusCode` to be `true`. |
| `retryOnNetworkFailure` | `true` | Whether Cypress retries the request after a transient network error. When `true`, Cypress retries up to 4 times. |
| `timeout` | [`pageLoadTimeout`](/llm/markdown/app/references/configuration.md#Timeouts) | Time to wait for `cy.visit()` to resolve before [timing out](#Timeouts). The request for the page can still time out sooner, at `responseTimeout` or the operating system's network limit. |

To change `pageLoadTimeout` and `baseUrl` for every `cy.visit()`, set them in your [Cypress configuration](/llm/markdown/app/references/configuration.md#Global).

### Yields

*   `cy.visit()` yields the `window` object after the page finishes loading.
*   It is [unsafe](/llm/markdown/app/core-concepts/retry-ability.md#Only-queries-are-retried) to chain further commands that rely on the yielded `window` after `cy.visit()`.

This example confirms `window.navigator.language` after visiting the site:

```
cy.visit('/') // yields the window object
  .its('navigator.language') // yields window.navigator.language
  .should('equal', 'en-US') // asserts the expected value
```

To work with the `window` directly, use `.then()`:

```
cy.visit('index.html').then((contentWindow) => {
  // contentWindow is the remote page's window object
})
```

## Examples

### URL

#### Visit a local server running on `http://localhost:8000`

`cy.visit()` resolves when the remote page fires its `load` event.

```
cy.visit('http://localhost:8000')
```

### Options

#### Change the `cy.visit()` page load timeout

The `timeout` option overrides the `pageLoadTimeout` from your [configuration](/llm/markdown/app/references/configuration.md#Timeouts) for this page load.

```
// Wait 30 seconds for page 'load' event
cy.visit('/index.html', { timeout: 30000 })
```

#### Add basic auth headers to `cy.visit()`

When your application uses [Basic Authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication), Cypress can send the credentials for you.

Provide the `username` and `password` in the `auth` object. Cypress then attaches them at the network level to every later request to the origin you're testing. Pass `log: false` to leave the visit out of the Command Log. Without it, clicking the `visit` row prints the `auth` object, password included, to the console. Keep in mind that `log: false` also hides the visit's URL and redirects, which you'd otherwise use when debugging a failed visit.

```
cy.visit('https://example.cypress.io/', {
  auth: {
    username: 'wile',
    password: 'coyote',
  },
  log: false,
})
```

You can also provide the username and password directly in the URL. In this form, the Command Log row shows the full URL, password included, so `log: false` matters even more: without it, the password appears in screenshots and videos of the run.

```
// this is the same thing as providing the auth object
cy.visit('https://wile:coyote@example.cypress.io', { log: false })
```

Cypress attaches the `Authorization` header for you on requests to the origin you visited. Other origins do not receive it. On the [legacy network path](/llm/markdown/app/guides/native-network-interception.md#Using-the-legacy-network-path) the header is attached outside of the browser, so it does **not** appear in DevTools.

#### Run code before the page loads with `onBeforeLoad`

Cypress calls `onBeforeLoad` as early as possible, before your page has loaded all of its resources. Your app's scripts haven't run yet, so this is the place to prepare the page before your app starts.

This example seeds a token in `localStorage` before the app reads it, and stubs `window.open` so the test can assert on it:

```
cy.visit('/#dashboard', {
  onBeforeLoad(win) {
    // win is the remote page's window object
    win.localStorage.setItem('token', 'abc123')
    cy.stub(win, 'open').as('windowOpen')
  },
})
cy.get('@windowOpen').should('not.have.been.called')
```

These recipes use the `onBeforeLoad` option to:

*   [Bootstrap your app](/llm/markdown/app/references/recipes.md#Server-Communication)
*   [Set a token in `localStorage` for login during single sign-on](/llm/markdown/app/references/recipes.md#Logging-In)
*   [Stub `window.fetch`](/llm/markdown/app/references/recipes.md#Stubbing-and-spying)

#### Run code after the page loads with `onLoad`

Cypress calls `onLoad` once your page has fired its `load` event. At this point, all of the page's scripts, stylesheets, HTML, and other resources are available.

```
cy.visit('/#/users', {
  onLoad: (contentWindow) => {
    // contentWindow is the remote page's window object
    if (contentWindow.angular) {
      // do something
    }
  },
})
```

#### Add query parameters to a `cy.visit()` URL

Pass query parameters as an object in the `qs` option.

```
// visits <baseUrl>/users?page=1&role=admin
cy.visit('/users', {
  qs: {
    page: '1',
    role: 'admin',
  },
})
```

Cypress merges the parameters in `qs` into any query parameters already on the `url`.

```
// visits https://example.cypress.io/users?page=1&admin=true
cy.visit('https://example.cypress.io/users?page=1', {
  qs: { admin: true },
})
```

#### Submit a form with a `cy.visit()` POST request

To send a request that looks like a user submitting an HTML form, use a `POST` method with a `body` containing the form values:

```
cy.visit({
  url: '/cgi-bin/newsletterSignup',
  method: 'POST',
  body: {
    name: 'Avery Quinlan',
    email: 'avery.quinlan@example.com',
  },
})
```

#### Send custom request headers with `cy.visit()`

Pass `headers` to send extra HTTP headers with the page request, such as a language preference or a feature flag your server reads. Cypress sends them only with the initial `cy.visit()` request, not with the requests the page makes afterward.

```
cy.visit('/', {
  headers: { 'Accept-Language': 'fr-FR' },
})
cy.contains('Bienvenue')
```

#### Visit an error page with `failOnStatusCode: false`

By default, `cy.visit()` fails when the server responds with a status code outside the `2xx` and `3xx` ranges. To test your 404 or 500 page, set `failOnStatusCode` to `false` and assert on what the page shows:

```
cy.visit('/does-not-exist', { failOnStatusCode: false })
cy.contains('h1', 'Page not found')
```

#### Retry `cy.visit()` while your server finishes starting

When your server answers with an error status for a few seconds after it starts, such as a `503` in CI, set `retryOnStatusCodeFailure` to `true`. Cypress retries the request up to 4 times before failing.

```
cy.visit('/', { retryOnStatusCodeFailure: true })
```

### Workflows

#### Log in once with `cy.session()` and visit in each test

Pair `cy.visit()` with [`cy.session()`](/llm/markdown/api/commands/session.md) to log in once, cache the session, and restore it before each test. Call `cy.visit()` after `cy.session()`, since Cypress clears the page each time it restores a session.

```
beforeEach(() => {
  cy.session('user', () => {
    cy.visit('/login')
    cy.get('#username').type('user')
    cy.get('#password').type('s3cret', { log: false })
    cy.get('form').submit()
    cy.location('pathname').should('eq', '/dashboard')
  })
  cy.visit('/dashboard')
})
```

## Notes

### How `cy.visit()` prefixes URLs with `baseUrl`

When `baseUrl` is set, Cypress prefixes the URL with it. Configure `baseUrl` in the [Cypress configuration](/llm/markdown/app/references/configuration.md) so you don't repeat the host in every `cy.visit()` command.

*   cypress.config.js
*   cypress.config.ts

```
const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    baseUrl: 'http://localhost:3000/#/',
  },
})
```

```
import { defineConfig } from 'cypress'

export default defineConfig({
  e2e: {
    baseUrl: 'http://localhost:3000/#/',
  },
})
```

```
cy.visit('dashboard') // Visits http://localhost:3000/#/dashboard
```

To visit a different host while `baseUrl` is set, provide the fully qualified URL.

```
cy.visit('https://example.cypress.io')
```

### Visit local files with `cy.visit()`

Cypress serves your files itself when you don't provide a host and `baseUrl` **is not defined**. The path is relative to your project's root folder (the directory that contains the [Cypress configuration file](/llm/markdown/app/references/configuration.md)), or to the [`fileServerFolder`](/llm/markdown/app/references/configuration.md#Folders--Files) if you've configured one. The `file://` protocol is not supported.

Having Cypress serve your files is useful in smaller projects and example apps, but we don't recommend it for production apps. Run your own server and provide its URL to Cypress instead.

```
cy.visit('app/index.html')
```

To visit a local file in a single test or group of tests while `baseUrl` is set, disable `baseUrl` with [per-test configuration](/llm/markdown/app/references/configuration.md#Test-Configuration). Given this Cypress configuration:

*   cypress.config.js
*   cypress.config.ts

```
const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    baseUrl: 'https://example.cypress.io',
  },
})
```

```
import { defineConfig } from 'cypress'

export default defineConfig({
  e2e: {
    baseUrl: 'https://example.cypress.io',
  },
})
```

The first test visits the `baseUrl`, while the second test visits the local file.

```
it('visits base url', () => {
  cy.visit('/')
  cy.contains('h1', 'Kitchen Sink')
})
it('visits local file', { baseUrl: null }, () => {
  cy.visit('index.html')
  cy.contains('local file')
})
```

### How `cy.visit()` follows redirects

`cy.visit()` follows redirects and resolves on the page it ends on:

```
// we aren't logged in, so our web server
// redirected us to /login
cy.visit('/admin')
cy.location('pathname').should('eq', '/login')
```

The Command Log shows each redirect after the URL you visited, with its status code and where it led:

### When `cy.visit()` adds the `http://` protocol for you

Cypress prepends the `http://` protocol to URLs that start with `localhost`, `0.0.0.0`, `127.0.0.1`, or `www.`, and to hosts with three or four dot-separated parts, such as `beta.example.com`. For any other host, such as `example.com`, provide the protocol. Otherwise Cypress treats the URL as a relative path.

```
cy.visit('localhost:3000') // Visits http://localhost:3000
cy.visit('0.0.0.0:3000') // Visits http://0.0.0.0:3000
cy.visit('127.0.0.1:3000') // Visits http://127.0.0.1:3000
cy.visit('www.example.com') // Visits http://www.example.com/
```

### How `cy.visit()` handles a URL that changes only the hash

When the URL you visit matches the current page except for the hash, the browser doesn't make a new request. `cy.visit()` resolves on the `hashchange` event instead of the `load` event, and `onBeforeLoad` is not called. If the hash is also the same as the current one, neither `onBeforeLoad` nor `onLoad` is called.

```
cy.visit('/#/users')
cy.visit('/#/settings') // no page reload
```

### Change the user agent for `cy.visit()`

To change the `User-Agent` header, see [how to override the browser's default user agent](/llm/markdown/app/faq.md#Can-I-override-or-change-the-default-user-agent-the-browser-uses).

### Intercept requests your app makes before `cy.visit()` resolves

A common need is to visit a page and stub the requests your app makes as soon as it starts. You might expect this to work:

```
// this code may not work depending on implementation
cy.visit('/#/app')
cy.intercept('GET', '/users/**', { fixture: 'users.json' })
```

If your app makes a request while it starts up, the code above can miss it. `cy.visit()` resolves once the page fires its `load` event, and Cypress doesn't process the [`cy.intercept()`](/llm/markdown/api/commands/intercept.md) command until _after_ that.

By then, many apps have already begun routing, initializing, and sending requests, so the route is registered too late to catch them.

Reverse the order of the commands:

```
// this code is probably what you want
cy.intercept('GET', '/users/**', { fixture: 'users.json' }).as('getUsers')
cy.visit('/#/app')
cy.wait('@getUsers')
```

Routes you register before `cy.visit()` are already active when the page starts loading, so they catch the requests your app makes as soon as it runs.

### Visiting cross-origin sites with `cy.visit()`

After visiting a cross-origin site, interact with its content inside a [`cy.origin()`](/llm/markdown/api/commands/origin.md) block.

When visiting a cross-origin site, the `onBeforeLoad` and `onLoad` options are not supported. Instead, register a `window:before:load` or `window:load` event listener inside a `cy.origin()` block for that origin, then visit it:

```
cy.visit('/')
cy.origin('https://auth.example.com', () => {
  cy.on('window:before:load', (win) => {
    // what you would have put in onBeforeLoad
    win.localStorage.setItem('returnTo', '/dashboard')
  })
})
cy.visit('https://auth.example.com/login')
```

## Rules

### Requirements

*   `cy.visit()` requires being chained off of `cy`.
*   `cy.visit()` requires the response to be `content-type: text/html` or `application/xhtml+xml`. When the response has no `content-type` header, Cypress checks whether the body is HTML.
*   `cy.visit()` requires the response code to be `2xx` or `3xx` after following redirects, unless `failOnStatusCode` is `false`.
*   `cy.visit()` requires the `load` event to eventually fire, unless the visit changes only the URL's hash.

### Assertions

*   `cy.visit()` automatically waits for assertions you have chained to pass.

### Timeouts

*   `cy.visit()` can time out waiting for the page to fire its `load` event.
*   `cy.visit()` can time out waiting for assertions you've added to pass.
*   `cy.visit()` fails with a network error if the server doesn't respond within [`responseTimeout`](/llm/markdown/app/references/configuration.md#Timeouts), even when `pageLoadTimeout` is longer.

## Command Log

This example visits the example application in a `beforeEach`:

```
beforeEach(() => {
  cy.visit('https://example.cypress.io/commands/viewport')
})
```

The commands above display in the Command Log as:

When you click `visit` in the Command Log, the console outputs the following:

## History

| Version | Changes |
| --- | --- |
| [14.0.0](/llm/markdown/app/references/changelog.md#14-0-0) | `cy.origin()` is required to visit a different origin in the same test, rather than a different superdomain |
| [11.0.0](/llm/markdown/app/references/changelog.md#11-0-0) | Removed `experimentalSessionAndOrigin` reference |
| [3.5.0](/llm/markdown/app/references/changelog.md#3-5-0) | Added support for options `qs` |
| [3.3.0](/llm/markdown/app/references/changelog.md#3-3-0) | Added support for options `retryOnStatusCodeFailure` and `retryOnNetworkFailure` |
| [3.2.0](/llm/markdown/app/references/changelog.md#3-2-0) | Added options `url`, `method`, `body`, and `headers` |
| [1.1.3](/llm/markdown/app/references/changelog.md#1-1-3) | Added option `failOnStatusCode` |
| [0.18.2](/llm/markdown/app/references/changelog.md#0-18-2) | Automatically send `Accept: text/html,*/*` request header |
| [0.18.2](/llm/markdown/app/references/changelog.md#0-18-2) | Automatically send `User-Agent` header |
| [0.17.0](/llm/markdown/app/references/changelog.md#0-17-0) | Cannot `cy.visit()` two different super domains in a single test |
| [0.6.8](/llm/markdown/app/references/changelog.md#0-6-8) | Added option `log` |
| [0.4.3](/llm/markdown/app/references/changelog.md#0-4-3) | Added option `onBeforeLoad` |
| [< 0.3.3](/llm/markdown/app/references/changelog.md#0-3-3) | `cy.visit()` command added |

## See also

*   [`cy.go()`](/llm/markdown/api/commands/go.md)
*   [`cy.reload()`](/llm/markdown/api/commands/reload.md)
*   [`cy.request()`](/llm/markdown/api/commands/request.md)
*   [`cy.origin()`](/llm/markdown/api/commands/origin.md)
*   [`cy.session()`](/llm/markdown/api/commands/session.md)
