How to Save Cookies and Reuse Authentication State in Playwright

We are going to learn How to Save Cookies and Reuse Authentication State in Playwright in this tutorial. Playwright makes storing your auth state easy and then reusing it in other tests. Thus avoiding the logging-in functionality each time you run your test. Doing so will make your tests run faster and eliminate any logging-related discrepancies that one might face owing to shared CPU usage and server load.

This tutorial aims to teach you how to save and reuse the authentication state in Playwright. Have easy and seamless execution once you add the code logic in place.

meme for google authentication

Isn’t that true about Google?

There are some caveats here though.

  • Remember, this is only valid for tests without any server-side state. Meaning if your tests are updating server side stuff then you need to have two different accounts for each test case.
  • Also remember, that the authentication needs to be browser-specific. The logic is not valid if you are using API for logging in. In many applications, API works very differently from the browser.

That being said, you should only use this method if you are running only independent tests in parallel that are not stepping on each other’s toes.

This tutorial assumes that you have already written code for logging into the browser. Because that step is the one that authenticates and generates the correct auth cookies crucial to reuse.

Steps on How to Save Cookies and Reuse Authentication State in Playwright

Step 1: Create a folder called playwright/.auth and place it in your explorer.

Create Playwright .auth in the beginning for How to Save Cookies and Reuse Authentication State in Playwright

Step 2: Gitignore it, meaning put the info in your .gitignore since you don’t want all the secure-auth info to go upstream.

gitignore playwright.auth for How to Save and Reuse Authentication State in Playwright tutorial

Step 3: Create an auth.setup.ts file in your tests folder.

create auth.setup.ts

In this auth.setup.ts we will be adding the real logic of authentication.

Step 4: You can either create a test file here or create an import like this:

import {test as setup, expect} from @playwright/test;

Step 5: Next create an authentication logic in setup since we are defining our test as setup like this:

setup('authenticate', async ({ page }) => {
});

Inside this setup or test will our logic go. Notice how we are pulling the page fixture to use page methods directly.

Step 6: Now based on your own URLs and authentication logics replace necessary things for authentication below:

setup('authenticate', async ({ page }) => {

//login
await page.goto("url goes here");
await page.locator('locator for username textbox').fill('username');
await page.locator('locator for password textbox').fill('password');
await page.locator('locator for submit button').click();

//Wait for login to fully complete, i.e. cookies to get set
await expect(page.locator("locator for some heading on dashboard")).toBeVisible();

//Set .auth file path
await page.context().storageState({ path: 'playwright/.auth/user.json' });
});

Here’s a snapshot from my project:

Add authentication logic in playwright

As you can see from the comments above we are performing three things. Initially we are logging in. Then we are waiting for the login to completely finish, which can be verified by waiting for some element to visible on the landing page of your app. Third is where we are setting the .auth path where the storageState will be stored.

We aren’t done yet. How would Playwright know that it is supposed to run the setup? We have to configure it right? So we have to create it as a project in config file and allow the config to look for the above setup file to run, then add it as a dependency in our original project.

Step 7: So that would mean open your playwright.config.ts file and navigate to your projects section and add the following as a project:

// Setup project
{ name: 'setup', testMatch: /.*\.setup\.ts/ },

It would look something like this:

Step 8: Next thing you gotta do is also use the prepared storage state by providing the playwright/.auth/user.json path.

So the part where your project is add the storage state path location in the use section like this, along with adding the project defined in Step 9 as a dependency:

{ 
name: 'chromium',
use: { ...devices['Desktop Chrome'],
storageState: 'playwright/.auth/user.json',
},
dependencies: ['setup']
}

So basically it would all appear together like this:

NOTE: If you are using multiple projects (e.g. for firefox, webkit etc., or even any other project), if you want to have the same authentication logic, yoi need to perform Step 9 for them as well.

That’s it!

Step 9: To test the above go ahead and create two test cases, and then run your tests to verify that the second one doesn’t need the authentication logic, since it uses the stored state from the setup file.

You will also notice a user.json file gets created which will have the cookies for the website which helps in logging in the next time you use a test.

user.json stores your authentication cookies How to Save and Reuse Authentication State in Playwright tutorial

If at some point you don’t want the stored cookies and want to kind of refresh things from start you can always delete the playwright folder that you created in Step 1 or just the playwright/.auth since that gets created new any way whenever you execute your tests.

Let me know in the comments section if you enjoyed learning How to Save and Reuse Authentication State in Playwright. There are more Playwright tutorials to explore, go bananas!

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

Leave a Reply