Cypress hosts configuration
Advent day 20: How to access a custom HTTPS domain using the "hosts" option in the cypress.json file
Imagine you have created a local site and now want to check if it works in HTTPS mode. You have created a self-signed certificate for the domain “my-secure-site”, started react-scripts with all the options, and now trying to access “https://my-secure-site:3000” … and it does not work.
$ brew install mkcert
$ mkcert -install
$ mkdir .cert
$ mkcert -key-file ./.cert/key.pem \
-cert-file ./.cert/cert.pem "my-secure-site"
$ HTTPS=true SSL_CRT_FILE=./.cert/cert.pem \
SSL_KEY_FILE=./.cert/key.pem npm start
The browser has no idea where the “my-secure-site” is running. It certainly does not look at the IP address 127.0.0.1:3000 where it is running.
Ok, the browser knows where to look for “localhost”, so maybe that will work.
Hmm, so the certificate we just created has a name other than “localhost”. So we go into the local system hosts file and start adding records and messing with the local network stack. Ughh.
Alternative solution: open the cypress.json
file and add the “hosts” object that maps each domain to an IP address, for example, “my-secure-site” is mapped to the address 127.0.0.1
{
"baseUrl": "https://my-secure-site:3000",
"hosts": {
"my-secure-site": "127.0.0.1"
}
}
Open Cypress and run cy.visit(‘/’)
- boom, the test is happily running against the local HTTPS site.
For more information, read my blog post “Cypress Hosts Option“ and see the code in bahmutov/cypress-local-https repo.
PS: the “hosts” option really needs to be documented on the Cypress Configuration page.
How can we map port with IP address?
How does host settings work for version 10 and above?