In this article we will learn how to to basic authentication using Nightwatch.
We will use the demo app called “The Internet” that has a use case around basic authentication
The demo app can be found here.
Use Case – Basic Authentication Nightwatch
Let us try to understand the use case. This case will be very common when testing websites that contain a basic authentication mechanism.
Before we do the automation setup, let us implement the use case manually.
Steps
- Go to “The Internet” website
- Click on “Basic Authentication” (Note that the username and password are mentioned as admin)

- Enter admin in the username field
- Enter admin in the password field
- Click on Sign In

You have successfully logged in using to a website using basic authentication manually. Now let’s proceed towards setting this up via an automation script using Nightwatch.
Script – Basic Authentication Nightwatch
If you directly open the URL using the navigateTo command, the script will get stuck where the basic authentication alert is shown. It will not enter the user name and password and you will not be able to continue your testing.
In order to avoid this issue, you have to pass the credentials in the http request headers. This can be done by using a command called registerBasicAuth(‘username’,’password’). Reference
You will have to register the basic authentication before opening the URL.
describe('basic authentication', function() {
it('Open URL and do Basic Authentication', function(browser) {
browser.registerBasicAuth('admin', 'admin');
browser
.navigateTo('http://the-internet.herokuapp.com/basic_auth')
.assert.textContains('#content .example h3','Basic Auth')
.assert.textContains('#content .example p','Congratulations');
});
});
Before opening the URL that contains basic authentication, we registered the basic authentication credentials as
- username – admin
- password – admin
Once this is done, in the subsequent requests, the basic authentication will be passed in the header requests and hence the test will not be stuck at the point where credentials are asked.
Conclusion
Basic authentication is a breeze with Nightwatch. You simply have to register the credentials and proceed with the testing of the website. The framework will handle the rest.