Goal: Use playwright for testing without having to log in multiple times as per documentation here.
Problem: Playwright tests not picking up session token from Next-Auth and hence am not able to reuse an authenticated status across mutiple tests.
My understanding is that Next-Auth checks for next-auth.session-token to validate the auth status. However following the above docs, I've noticed that the session token never get's stored in the storageState.json. If I manually add in the session token to the JSON then the tests work as expected.
Here is a very barebones repo I've setup with just a login button and one test.
Here's the typical [...nextAuth].js
import GithubProvider from "next-auth/providers/github";
export const authOptions = {
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
secret: process.env.NEXTAUTH_SECRET,
debug: true,
};
export default NextAuth(authOptions);
Here's the global-setup.js for Playwright with email/password swapped out
module.exports = async () => {
const browser = await chromium.launch({
headless: false,
});
const page = await browser.newPage();
await page.goto('http://localhost:3000/');
await page.getByRole('button', { name: 'Sign in' }).click();
await page.getByRole('button', { name: 'Sign in with GitHub' }).click();
await page
.getByLabel('Username or email address')
.fill('email');
await page.getByLabel('Password').fill('password');
await page.getByRole('button', { name: 'Sign in' }).click();
await page.context().storageState({ path: 'storageState.json' });
await browser.close();
};
Here's the e2e test I'm running
const { test, expect } = require("@playwright/test");
test.use({
storageState: "storageState.json",
});
test("sign in through github", async ({ page }) => {
await page.goto("http://localhost:3000");
await expect(page.getByText("Signed in as")).not.toBeEmpty();
});
I expect the auth state to be stored in storageState.json from the code in global-setup.js. It does indeed store information there but it's missing the next-auth.session-token for some reason and hence causes the tests I'm running to fail.