### Build and Start Application Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/INTEGRATION_GUIDE.md Build the application for production and start the server. ```bash pnpm run build pnpm run start ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/README.md Installs all necessary project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Clerk Environment Variables Example Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-nextjs.md Example of how to configure Clerk authentication using environment variables in a .env.local file. ```bash NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_XXXX CLERK_SECRET_KEY=sk_test_XXXX NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up NEXT_PUBLIC_CLERK_SIGN_IN_FORCE_REDIRECT_URL=/protected NEXT_PUBLIC_CLERK_SIGN_UP_FORCE_REDIRECT_URL=/protected ``` -------------------------------- ### Vercel Deployment Setup Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/INTEGRATION_GUIDE.md Steps for deploying your application to Vercel, including environment variable configuration. ```bash NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY CLERK_SECRET_KEY Other custom variables ``` -------------------------------- ### Copy Environment File Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/README.md Copies the example environment file to a local configuration file. Ensure you fill in your specific values. ```bash cp .env.local.example .env.local ``` -------------------------------- ### Example .env.local for Clerk, Playwright, and Next.js Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/configuration.md This snippet shows a complete example of the .env.local file, including all necessary Clerk frontend and backend keys, sign-in/sign-up URLs, and E2E test credentials. Ensure these variables are set correctly for your application and testing environment. ```bash # Clerk Frontend Keys NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_abc123xyz789 NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up NEXT_PUBLIC_CLERK_SIGN_IN_FORCE_REDIRECT_URL=/protected NEXT_PUBLIC_CLERK_SIGN_UP_FORCE_REDIRECT_URL=/protected # Clerk Backend CLERK_SECRET_KEY=sk_test_def456uvw123 # E2E Test Configuration E2E_CLERK_USER_EMAIL=e2e+clerk_test@example.com E2E_CLERK_USER_PASSWORD=SecureTestPassword123! # Server Configuration PORT=3000 ``` -------------------------------- ### Install Dependencies and Playwright Browsers Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/INTEGRATION_GUIDE.md Install project dependencies using pnpm and download the necessary Playwright browser binaries. ```bash pnpm install pnpm exec playwright install chromium ``` -------------------------------- ### Run Next.js Development Server Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/README.md Starts the Next.js development server for local testing and development. ```bash pnpm run dev ``` -------------------------------- ### Configure SignUp Page Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-nextjs.md Example of setting up the sign-up page in Next.js using the SignUp component. Configure the 'forceRedirectUrl' to redirect users to a specific page after successful signup. ```typescript // app/sign-up/[[...sign-up]]/page.tsx import { SignUp } from "@clerk/nextjs"; export default function SignUpPage() { return (

Sign Up

); } ``` -------------------------------- ### Default Server Component Example Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/nextjs-core.md A basic example of a Server Component that fetches data. Server Components can access databases, secrets, environment variables, and backend services. ```typescript // Server component (default) export default async function Page() { const data = await fetch("https://api.example.com/data"); return
{data}
; } ``` -------------------------------- ### Configure SignIn Page Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-nextjs.md Example of setting up the sign-in page in Next.js using the SignIn component. Ensure the 'path' prop matches the page's URL structure. ```typescript // app/sign-in/[[...sign-in]]/page.tsx import { SignIn } from "@clerk/nextjs"; export default function SignInPage() { return (

Sign In

); } ``` -------------------------------- ### Playwright Configuration Example Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/configuration.md Example configuration for Playwright, including test directory, web server settings, and project definitions for different test types. ```typescript export default defineConfig({ testDir: path.join(__dirname, "e2e"), outputDir: "test-results/", webServer: { command: "npm run dev", url: `http://localhost:${PORT}`, reuseExistingServer: !process.env.CI, }, use: { baseURL: `http://localhost:${PORT}`, trace: "retry-with-trace", }, projects: [ { name: "global setup", testMatch: /global\.setup\.ts/, teardown: "global teardown", }, { name: "Main tests", testMatch: /.*app.spec.ts/, dependencies: ["global setup"], }, { name: "Authenticated tests", testMatch: /.*authenticated.spec.ts/, use: { storageState: "playwright/.clerk/user.json", }, dependencies: ["global setup"], }, { name: "global teardown", testMatch: /global\.teardown\.ts/, }, ], }); ``` -------------------------------- ### Client Component Example Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/nextjs-core.md An example of a Client Component marked with 'use client'. Client Components run in the browser and are suitable for interactive features, browser APIs, and client-only libraries. ```typescript 'use client'; export default function ClientComponent() { const [count, setCount] = useState(0); return ; } ``` -------------------------------- ### Run Next.js Production Build Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/README.md Starts the Next.js application after it has been built for production. ```bash pnpm run start ``` -------------------------------- ### Clerk Frontend Configuration Example Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/configuration.md Set these environment variables in your .env.local file for client-side Clerk integration. Variables prefixed with NEXT_PUBLIC_ are exposed to the browser. ```bash NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_abc123def456 NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up NEXT_PUBLIC_CLERK_SIGN_IN_FORCE_REDIRECT_URL=/protected NEXT_PUBLIC_CLERK_SIGN_UP_FORCE_REDIRECT_URL=/protected ``` -------------------------------- ### Clerk Backend Configuration Example Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/configuration.md Configure your secret key in .env.local for server-side Clerk operations. This variable is not exposed to the browser and must be kept secure. ```bash CLERK_SECRET_KEY=sk_test_xyz789abc123 ``` -------------------------------- ### Async Server Component with Clerk Auth (Project Example) Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/nextjs-core.md A practical example from the project showing an async Server Component performing an authentication check using Clerk. This pattern is used in `app/protected/page.tsx`. ```typescript //app/protected/page.tsx import { auth } from "@clerk/nextjs/server"; export default async function Page() { const { userId } = await auth(); // Async auth check return

User ID: {userId}

; } ``` -------------------------------- ### Test Configuration Example Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/configuration.md Set test user credentials and development server port in .env.local. The email should use the '+clerk_test' suffix for Clerk to suppress email delivery. ```bash E2E_CLERK_USER_EMAIL=e2e+clerk_test@example.com E2E_CLERK_USER_PASSWORD=TestPassword123! PORT=3000 ``` -------------------------------- ### Install Playwright Test Dependencies Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/README.md Installs the required Playwright browsers for running end-to-end tests. ```bash pnpm exec playwright install chromium ``` -------------------------------- ### Global Setup for Authentication Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/next-auth-flow.md Sets up an authenticated session before tests run by signing in via the UI and saving the session state to a file. This file can then be reused to skip login in subsequent tests. ```typescript setup("authenticate", async ({ page }) => { await page.goto("/"); await clerk.signIn({ page, emailAddress: process.env.E2E_CLERK_USER_EMAIL!, }); await page.goto("/protected"); await page.waitForSelector("h1:has-text('This is a PROTECTED page')"); // Save authenticated session state await page.context().storageState({ path: authFile }); }); ``` -------------------------------- ### Navigate and Interact with a Page Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/playwright-test.md This example demonstrates navigating to a URL and extracting text content from an element using the `page` fixture. ```typescript import { test } from "@playwright/test"; test("navigate to page", async ({ page }) => { await page.goto("/"); const title = await page.locator("h1").textContent(); console.log(title); }); ``` -------------------------------- ### Basic Clerk Middleware Setup Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/nextjs-core.md Implement a basic middleware function in proxy.ts or middleware.ts to handle requests before they reach the page. This is commonly used for authentication. ```typescript // proxy.ts (or middleware.ts) import { clerkMiddleware } from "@clerk/nextjs/server"; export default clerkMiddleware((auth, req) => { // Request handler }); export const config = { matcher: [/* route patterns */] }; ``` -------------------------------- ### clerkSetup Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-testing-playwright.md Initializes the Clerk testing environment. This function must be called in your global setup before running any Playwright tests. It can optionally load environment variables from a .env file. ```APIDOC ## clerkSetup ### Description Initializes the Clerk testing environment. Must be called in global setup before running any tests. When `dotenv` is false, environment variables must be pre-loaded by the calling code. ### Function Signature ```typescript function clerkSetup(options: { dotenv?: boolean; }): Promise ``` ### Parameters #### Options - **dotenv** (boolean) - Optional - Whether to load environment variables from .env file. Defaults to true. ### Return Type `Promise` ### Example ```typescript import { clerkSetup } from "@clerk/testing/playwright"; import { test as setup } from "@playwright/test"; setup("global setup", async () => { await clerkSetup({ dotenv: false }); }); ``` ``` -------------------------------- ### Sync User Data to Database Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/INTEGRATION_GUIDE.md After authentication, retrieve user details using `currentUser` and save them to your database. This example shows how to store basic user information like ID, email, and name. ```typescript // app/api/user/sync/route.ts import { auth, currentUser } from "@clerk/nextjs/server"; import { NextResponse } from "next/server"; export async function POST() { const { userId } = await auth(); const user = await currentUser(); if (!userId) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } // Save to your database await db.users.create({ clerkId: userId, email: user?.emailAddresses[0]?.emailAddress, name: `${user?.firstName} ${user?.lastName}`, }); return NextResponse.json({ ok: true }); } ``` -------------------------------- ### Initialize Clerk Testing Utilities Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/TEST_ARCHITECTURE.md Initializes Clerk testing utilities within the global setup. `dotenv: false` is used as environment variables are already loaded by the test runner. ```typescript setup("global setup", async () => { await clerkSetup({ dotenv: false }); ``` -------------------------------- ### Initialize Clerk for Testing Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-testing-playwright.md Initializes the Clerk testing environment. Must be called in global setup before running any tests. Set `dotenv` to false if environment variables are pre-loaded. ```typescript import { clerkSetup } from "@clerk/testing/playwright"; import { test as setup } from "@playwright/test"; setup("global setup", async () => { await clerkSetup({ dotenv: false }); }); ``` -------------------------------- ### Configure Playwright Web Server Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/TEST_ARCHITECTURE.md Sets up the web server configuration for Playwright tests. It starts the Next.js development server and waits for it to be ready. The server is reused unless running in a CI environment to avoid port conflicts. ```typescript webServer: { command: "npm run dev", url: baseURL, reuseExistingServer: !process.env.CI, } ``` -------------------------------- ### Setup Clerk Testing Token for API Access Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-testing-playwright.md Injects a testing token into the page context to enable API calls that require user authentication. Useful for simulating user actions during signup/signin flows. ```typescript import { setupClerkTestingToken } from "@clerk/testing/playwright"; import { test } from "@playwright/test"; test("sign up flow", async ({ page }) => { await setupClerkTestingToken({ page }); await page.goto("/sign-up"); // Continue with signup flow }); ``` -------------------------------- ### Clone or Reference Repository Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/INTEGRATION_GUIDE.md Use this repository as a template or reference for your own project. Option A clones it as a new project, while Option B suggests copying relevant files. ```bash git clone my-clerk-app cd my-clerk-app ``` ```bash # Copy relevant files (middleware, layout, test setup, etc.) ``` -------------------------------- ### Manual Sign-In Steps Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/next-auth-flow.md This snippet outlines the manual steps to perform a sign-in, including navigating to the page, filling in the identifier, and submitting credentials. ```typescript await page.goto("/sign-in"); await page.locator("input[name=identifier]").fill(emailAddress); await page.getByRole("button", { name: "Continue" }).click(); await page.locator("input[name=password]").fill(process.env.E2E_CLERK_USER_PASSWORD!); await page.getByRole("button", { name: "Continue" }).click(); await page.getByRole("textbox", { name: "Enter verification code" }).pressSequentially("424242"); ``` -------------------------------- ### Server Component Protected Page Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-nextjs.md Example of a Next.js server component that protects a page by checking for a user ID and redirecting if not authenticated. ```typescript // app/protected/page.tsx import { auth } from "@clerk/nextjs/server"; import { redirect } from "next/navigation"; export default async function ProtectedPage() { const {userId} = await auth(); if (!userId) { redirect("/sign-in"); } return (

Protected Content

You are logged in as: {userId}

); } ``` -------------------------------- ### Clerk Sign-Up Page with Catch-All Route and Redirect Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-nextjs.md Configures the sign-up page using Next.js catch-all route syntax and specifies a force redirect URL upon successful sign-up. ```typescript // app/sign-up/[[...sign-up]]/page.tsx import { SignUp } from "@clerk/nextjs"; export default function SignUpPage() { return ; } ``` -------------------------------- ### Get User List Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-backend.md Retrieves a paginated list of users. Can filter by email addresses. Returns an empty array if no matches are found. ```typescript function getUserList(options?: { emailAddress?: string[]; limit?: number; offset?: number; }): Promise<{ data: User[] }>{ // Implementation details omitted } ``` ```typescript const client = createClerkClient({ secretKey }); // Find user by email const { data: users } = await client.users.getUserList({ emailAddress: ["test@example.com"] }); if (users.length > 0) { console.log("User exists:", users[0].id); } else { console.log("User not found"); } ``` -------------------------------- ### Protect Routes with Middleware Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/INTEGRATION_GUIDE.md Update the middleware to include additional routes that require authentication. This example shows how to protect /dashboard and /profile routes. ```typescript const isProtectedRoute = createRouteMatcher([ "/protected(.*)", "/dashboard(.*)", "/profile(.*)", "/admin(.*)" ]); ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/INTEGRATION_GUIDE.md Edit the .env.local file to add your Clerk API keys and configure application settings. Ensure you replace placeholder keys with your actual ones. ```bash NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_YOUR_KEY CLERK_SECRET_KEY=sk_test_YOUR_KEY NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up NEXT_PUBLIC_CLERK_SIGN_IN_FORCE_REDIRECT_URL=/protected NEXT_PUBLIC_CLERK_SIGN_UP_FORCE_REDIRECT_URL=/protected E2E_CLERK_USER_EMAIL=test+clerk_test@example.com E2E_CLERK_USER_PASSWORD=TestPassword123! ``` -------------------------------- ### Update Production Sign-in/Sign-up URLs Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/INTEGRATION_GUIDE.md Adjust the environment variables for sign-in and sign-up URLs if they have been customized. ```bash NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up ``` -------------------------------- ### Set up .env.local for E2E Tests Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/INTEGRATION_GUIDE.md Ensure your .env.local file exists and contains the E2E_CLERK_USER_EMAIL variable for end-to-end tests to run correctly. ```bash cp .env.local.example .env.local # Edit .env.local with your values ``` -------------------------------- ### Access Clerk API in Browser Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/next-auth-flow.md Directly access the Clerk API from the browser using `window.Clerk` to get the user object or the current session ID. ```typescript const user = window.Clerk.user; // User object or null const sessionId = window.Clerk.session?.id; // Current session ``` -------------------------------- ### Run Tests in Debug Mode Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/TEST_ARCHITECTURE.md Start Playwright tests in debug mode. This mode pauses execution on test failures, allowing for detailed inspection of the state. ```bash pnpm exec playwright test --debug ``` -------------------------------- ### SignUp Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-nextjs.md The SignUp component renders the Clerk sign-up form for new user account creation. It collects user data, handles email verification via OTP, and manages account creation and session initialization, including automatic redirection after signup. ```APIDOC ## SignUp ### Description Renders the Clerk sign-up form component for new user account creation. It collects user data, handles email verification via OTP, and manages account creation and session initialization, including automatic redirection after signup. ### Props | Prop | Type | Required | Default | Description | |------|------|----------|---------|-------------| | path | string | Yes | — | Current path where component mounted (e.g., `/sign-up`) | | routing | string | No | "path" | How routes are handled: "path" (URL) or "hash" (fragment) | | forceRedirectUrl | string | No | — | URL to redirect after successful signup | | signInUrl | string | No | — | URL to sign-in page (shown on signin link) | ### Usage ```typescript import { SignUp } from "@clerk/nextjs"; export default function SignUpPage() { return (

Sign Up

); } ``` ``` -------------------------------- ### Add Test for Dashboard Access Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/INTEGRATION_GUIDE.md Extend end-to-end tests by adding a new test case to verify that the dashboard is accessible when a user is authenticated. This example uses Playwright. ```typescript test("dashboard accessible when authenticated", async ({ page }) => { await page.goto("/dashboard"); await page.waitForSelector("h1:has-text('Dashboard')"); // Add assertions for dashboard content }); ``` -------------------------------- ### Set Production Clerk Instance Keys Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/INTEGRATION_GUIDE.md Configure your production environment with live Clerk publishable and secret keys. ```bash NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_live_YOUR_PROD_KEY CLERK_SECRET_KEY=sk_live_YOUR_PROD_SECRET ``` -------------------------------- ### Build Next.js for Production Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/README.md Compiles the Next.js application for production deployment. ```bash pnpm run build ``` -------------------------------- ### Pre-Authenticated State Configuration Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-testing-playwright.md Configures Playwright to use stored session state for skipping authentication in subsequent tests. The storage state is typically generated during a global setup. ```typescript // In playwright.config.ts { name: "authenticated tests", use: { storageState: "playwright/.clerk/user.json", } } // In test test("access protected page", async ({ page }) => { await page.goto("/protected"); await page.waitForSelector("h1:has-text('Protected')"); }); ``` -------------------------------- ### Navigate to Sign-In Page Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/next-auth-flow.md Use this snippet to initiate the sign-in process by navigating to the sign-in page in the browser. ```typescript await page.goto("/sign-in"); ``` -------------------------------- ### Project package.json Configuration Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/configuration.md Defines the project's name, version, scripts, and dependencies, including Clerk, Next.js, React, and Playwright. Key versions for major dependencies are also highlighted. ```json { "name": "playwright-clerk-nextjs-example", "version": "0.0.1", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint", "test:e2e": "playwright test" }, "dependencies": { "@clerk/nextjs": "^7.0.8", "next": "^16.2.2", "react": "^19.2.4", "react-dom": "^19.2.4" }, "devDependencies": { "@clerk/backend": "^3.2.4", "@clerk/testing": "^2.0.8", "@playwright/test": "^1.59.1", "@types/node": "^25.5.2", "@types/react": "^19.2.14", "typescript": "^6.0.2" }, "packageManager": "pnpm@10.33.4+sha512..." } ``` -------------------------------- ### Get Current User on Server Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/README.md Retrieve the authenticated user's information on the server-side in your Next.js application. This allows you to access user details like ID and other profile information. ```typescript import { auth, currentUser } from "@clerk/nextjs/server"; const { userId } = await auth(); const user = await currentUser(); // Full user object ``` -------------------------------- ### SignUp Component Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/API_SUMMARY.md The SignUp component renders the sign-up form, facilitating user registration. It requires a `path` prop and allows configuration for routing, sign-in redirection, and post-signup redirects. ```APIDOC ## SignUp Component ### Description React component that renders the sign-up form, guiding users through the registration process. It can be configured with various options including routing and redirect URLs. ### Type React Component ### Location `app/sign-up/[[...sign-up]]/page.tsx` ### Props #### Path Parameters - **path** (string) - Required - The mounted path for the sign-up form (e.g., `/sign-up`). #### Query Parameters - **routing** (string) - Optional - The routing strategy to use (`path` or `hash`). - **forceRedirectUrl** (string) - Optional - The URL to redirect to after a successful signup. - **signInUrl** (string) - Optional - The URL to redirect to for sign-in. ### Purpose Facilitates new user registration and account creation. ``` -------------------------------- ### Example of Missing Environment Variables Error Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/configuration.md This error message indicates that essential environment variables for Playwright tests are not set. Ensure that E2E_CLERK_USER_EMAIL and E2E_CLERK_USER_PASSWORD are defined in your environment or .env.local file. ```text Error: Please provide E2E_CLERK_USER_EMAIL and E2E_CLERK_USER_PASSWORD environment variables. ``` -------------------------------- ### Docker Deployment Configuration Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/INTEGRATION_GUIDE.md Dockerfile for building a Docker image of your Next.js application. ```dockerfile FROM node:20-alpine WORKDIR /app COPY package.json pnpm-lock.yaml ./ RUN npm install -g pnpm && pnpm install --frozen-lockfile COPY . . RUN pnpm run build EXPOSE 3000 CMD ["pnpm", "start"] ``` -------------------------------- ### page.goto Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/playwright-test.md Navigates to a specified URL. It can handle both relative paths (based on a configured baseURL) and absolute URLs. The navigation can be considered complete based on different states like 'load', 'domcontentloaded', or 'networkidle'. ```APIDOC ## page.goto ### Description Navigates to a URL. Returns response object if navigation succeeds, null if page closed. Uses relative paths based on `baseURL` from config. ### Method `page.goto(url: string, options?: GotoOptions): Promise` ### Parameters #### Path Parameters - **url** (string) - Required - URL or path to navigate to #### Query Parameters - **waitUntil** (string) - Optional - When to consider navigation complete: "load", "domcontentloaded", "networkidle" ### Request Example ```typescript await page.goto("/sign-up"); // Relative path await page.goto("https://example.com/page"); // Absolute URL ``` ### Response #### Success Response (200) - **Response | null** - Response object if navigation succeeds, null if page closed. ``` -------------------------------- ### Playwright Configuration Dependencies Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/TEST_ARCHITECTURE.md Defines dependencies between Playwright test projects. 'Main tests' and 'Authenticated tests' depend on 'global setup' for shared state. 'global teardown' runs last. ```typescript { name: "Main tests", dependencies: ["global setup"] } { name: "Authenticated tests", dependencies: ["global setup"], use: { storageState: "playwright/.clerk/user.json" } } { name: "global teardown" // No explicit dependency, but runs last } ``` -------------------------------- ### setupClerkTestingToken Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-testing-playwright.md Injects a Clerk testing token into the browser context, allowing API calls that normally require user authentication. This is particularly useful for simulating user actions during signup or signin flows. ```APIDOC ## setupClerkTestingToken ### Description Injects a testing token into the page context, enabling API calls that would normally require user authentication. Used when simulating user actions that trigger API requests during signup/signin flows. ### Function Signature ```typescript function setupClerkTestingToken(options: { page: Page; }): Promise ``` ### Parameters #### Options - **page** (Page) - Required - Playwright Page instance. ### Return Type `Promise` ### Example ```typescript import { setupClerkTestingToken } from "@clerk/testing/playwright"; import { test } from "@playwright/test"; test("sign up flow", async ({ page }) => { await setupClerkTestingToken({ page }); await page.goto("/sign-up"); // Continue with signup flow }); ``` ``` -------------------------------- ### Protect a Page in Next.js Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/API_SUMMARY.md Use the `auth` function from `@clerk/nextjs/server` to get the authenticated user ID. If no user is found, display a 'Not authenticated' message. Otherwise, render protected content. ```typescript import { auth } from "@clerk/nextjs/server"; export default async function Page() { const {userId} = await auth(); if (!userId) return
Not authenticated
; return
Protected content for {userId}
; } ``` -------------------------------- ### Get User ID in Server Components Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/API_SUMMARY.md Use the `auth()` function in server components to retrieve the current user's ID and session information. This is essential for implementing authentication checks. ```typescript const { userId } = await auth(); ``` -------------------------------- ### Simulate User Sign-In Flow Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/README.md Automates the user sign-in process by navigating to the sign-in page and filling in credentials. ```typescript await page.goto("/sign-in"); await page.locator("input[name=identifier]").fill("test@example.com"); await page.getByRole("button", { name: "Continue" }).click(); await page.locator("input[name=password]").fill("password"); await page.getByRole("button", { name: "Continue" }).click(); await page.getByRole("textbox", { name: "Enter verification code" }).pressSequentially("424242"); await page.waitForURL("**/protected"); ``` -------------------------------- ### Render SignUp Component Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-nextjs.md Use the SignUp component to render the Clerk sign-up form for new user account creation. Specify the 'path', 'routing', and 'forceRedirectUrl' to control the signup flow and redirection. ```typescript import { SignUp } from "@clerk/nextjs"; interface SignUpProps { path: string; // URL path where component is mounted routing?: "path" | "hash"; // Routing mode (default: "path") forceRedirectUrl?: string; // URL to redirect after signup signInUrl?: string; // URL to sign-in page (shown on signin link) [key: string]: any; // Additional props } export default function SignUpPage() { return ; } ``` -------------------------------- ### Clerk Sign-In Page with Catch-All Route Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-nextjs.md Configures the sign-in page using Next.js catch-all route syntax to handle sub-routes for Clerk's sign-in flow. ```typescript // app/sign-in/[[...sign-in]]/page.tsx import { SignIn } from "@clerk/nextjs"; export default function SignInPage() { return ; } ``` -------------------------------- ### Signup with Unique Email Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-testing-playwright.md Generates a unique email address using a timestamp for signup flows to prevent email collisions in concurrent test runs. Requires Clerk testing token setup. ```typescript import { setupClerkTestingToken, clerk } from "@clerk/testing/playwright"; import { test } from "@playwright/test"; test("signup flow", async ({ page }) => { await setupClerkTestingToken({ page }); const email = `e2e-signup-${Date.now()}+clerk_test@example.com`; await page.goto("/sign-up"); await page.locator("input[name=emailAddress]").fill(email); await page.locator("input[name=password]").fill(process.env.E2E_CLERK_USER_PASSWORD!); await page.getByRole("button", { name: "Continue" }).click(); // Verification code for +clerk_test emails is always 424242 await page.getByRole("textbox", { name: "Enter verification code" }).pressSequentially("424242"); await page.waitForURL("**/protected"); }); ``` -------------------------------- ### Next.js File Structure for Clerk Integration Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/PROJECT_OVERVIEW.md Illustrates the directory structure for a Next.js application integrating Clerk authentication, including app routes, E2E tests, middleware, and Playwright configurations. ```tree clerk-playwright-nextjs/ ├── app/ │ ├── layout.tsx │ ├── page.tsx │ ├── about/page.tsx │ ├── protected/page.tsx │ ├── sign-in/[[...sign-in]]/page.tsx │ └── sign-up/[[...sign-up]]/page.tsx ├── e2e/ │ ├── global.setup.ts │ ├── global.teardown.ts │ ├── app.spec.ts │ └── authenticated.spec.ts ├── playwright.config.ts ├── proxy.ts ├── playwright/ │ └── .clerk/ │ ├── user.json │ └── signup-user.json └── .env.local.example ``` -------------------------------- ### Protected Page with Clerk Authentication Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/nextjs-core.md Example of a protected page component in Next.js that fetches the authenticated user ID using Clerk's auth function. This demonstrates server-side authentication checks within a page. ```typescript // app/protected/page.tsx import { auth } from "@clerk/nextjs/server"; export default async function Page() { const {userId} = await auth(); return (

This is a PROTECTED page

Hi, {userId || "anonymous"}!

); } ``` -------------------------------- ### Define Playwright Test Projects Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/TEST_ARCHITECTURE.md Configures different Playwright projects with their respective test file patterns, dependencies, and setup/teardown routines. This allows for organizing tests into logical groups, such as global setup, main tests, and authenticated tests. ```typescript projects: [ { name: "global setup", testMatch: /global\.setup\.ts/, teardown: "global teardown", }, { name: "Main tests", testMatch: /.*app.spec.ts/, dependencies: ["global setup"], }, { name: "Authenticated tests", testMatch: /.*authenticated.spec.ts/, use: { storageState: "playwright/.clerk/user.json" }, dependencies: ["global setup"], }, { name: "global teardown", testMatch: /global\.teardown\.ts/, }, ] ``` -------------------------------- ### Submit Sign-Up Form Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/next-auth-flow.md Clicks the 'Continue' button to submit the filled sign-up form. ```typescript await page.getByRole("button", { name: "Continue", exact: true }).click(); ``` -------------------------------- ### createClerkClient() Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/API_SUMMARY.md Creates an authenticated backend API client for Clerk. This function is intended for server-side use only. ```APIDOC ## createClerkClient() ### Description Create an authenticated backend API client for Clerk. This function is intended for server-side use only. ### Parameters - **secretKey** (string) - Required - The secret key for authentication. ### Returns `ClerkClient` - An instance of the Clerk client. ``` -------------------------------- ### Render SignIn Component Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-nextjs.md Integrate the SignIn component to display the Clerk sign-in form. Configure the 'path' and 'routing' props to match your application's routing setup. This component handles the complete email/password and OTP verification flow. ```typescript import { SignIn } from "@clerk/nextjs"; interface SignInProps { path: string; // URL path where component is mounted routing?: "path" | "hash"; // Routing mode (default: "path") signUpUrl?: string; // URL to sign-up page [key: string]: any; // Additional props } export default function SignInPage() { return ; } ``` -------------------------------- ### Catch-All Route for Sign-In Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/nextjs-core.md Handles dynamic routing for sign-in flows, allowing Clerk UI components to manage sub-routing. The root path also matches. ```typescript // app/sign-in/[[...sign-in]]/page.tsx export default function Page() { return ; } ``` -------------------------------- ### auth() Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-nextjs.md Server-side function to retrieve the current user's authentication state. It can be called in server components or API routes to check authentication status, get user IDs, and access session information. Returns null for userId if the user is not authenticated. ```APIDOC ## auth() ### Description Server-side function to retrieve current user's authentication state. ### Method Server-side function call ### Parameters None ### Return Type ```typescript { userId: string | null; sessionId?: string; [key: string]: any; } ``` ### Example ```typescript import { auth } from "@clerk/nextjs/server"; const authState = await auth(); // Type: { userId: string | null; sessionId?: string; ... } // app/protected/page.tsx import { auth } from "@clerk/nextjs/server"; export default async function ProtectedPage() { const { userId } = await auth(); return (

Protected Page

{userId ? (

Hello, {userId}!

) : (

Not authenticated

)}
); } ``` ``` -------------------------------- ### Get Authentication State with auth() Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-nextjs.md Use the auth() function in server components or API routes to retrieve the current user's authentication state. It returns an object containing userId, sessionId, and other auth properties. userId will be null if the user is not authenticated. ```typescript import { auth } from "@clerk/nextjs/server"; const authState = await auth(); // Type: { userId: string | null; sessionId?: string; ... } ``` ```typescript // app/protected/page.tsx import { auth } from "@clerk/nextjs/server"; export default async function ProtectedPage() { const { userId } = await auth(); return (

Protected Page

{userId ? (

Hello, {userId}!

) : (

Not authenticated

)}
); } ``` -------------------------------- ### Create Clerk Backend Client Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-backend.md Instantiate the Clerk backend client using your secret key. Ensure the secret key is kept secure and not exposed client-side. ```typescript import { createClerkClient } from "@clerk/backend"; const client = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY! }); const users = await client.users.getUserList(); ``` -------------------------------- ### Backend User Creation and UI Signin Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/clerk-testing-playwright.md Creates a test user via the Clerk Backend API using a secret key, then signs in that user through the UI. Ensures the user exists before attempting UI sign-in. ```typescript import { createClerkClient } from "@clerk/backend"; import { clerk } from "@clerk/testing/playwright"; import { test } from "@playwright/test"; test("signin with backend-created user", async ({ page }) => { const client = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY! }); const email = `test-${Date.now()}+clerk_test@example.com`; await client.users.createUser({ emailAddress: [email], password: process.env.E2E_CLERK_USER_PASSWORD! }); await clerk.signIn({ page, emailAddress: email }); }); ``` -------------------------------- ### Environment Variables for .env.local Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/TEST_ARCHITECTURE.md Configure these environment variables in your `.env.local` file for test execution. They are essential for backend API access, frontend initialization, and test user authentication. ```bash NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_XXXX CLERK_SECRET_KEY=sk_test_XXXX E2E_CLERK_USER_EMAIL=e2e+clerk_test@example.com E2E_CLERK_USER_PASSWORD=TestPassword123! ``` -------------------------------- ### Test Signin Flow with Backend User Creation Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/TEST_ARCHITECTURE.md Tests the user signin process by first creating a user via the Clerk API using `createClerkClient`. This allows the test to run independently and track the user immediately. ```typescript test("sign in", async ({ page }) => { await setupClerkTestingToken({ page }); const signInEmail = `e2e-signin-${Date.now()}+clerk_test@example.com`; const client = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY!, }); const user = await client.users.createUser({ emailAddress: [signInEmail], password: process.env.E2E_CLERK_USER_PASSWORD!, firstName: "Test", lastName: "User", }); trackCreatedUser(user.id, signInEmail); await page.goto("/sign-in"); await page.waitForSelector(".cl-signIn-root", { state: "attached" }); await page.locator("input[name=identifier]").fill(signInEmail); await page.getByRole("button", { name: "Continue", exact: true }).click(); // ... complete signin flow }); ``` -------------------------------- ### Create User via Clerk Backend SDK Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/README.md Programmatically creates a new user in Clerk using the backend SDK. Ensure the `secretKey` is securely managed. ```typescript const client = createClerkClient({ secretKey }); const user = await client.users.createUser({ emailAddress: ["test@example.com"], password: "Password123!" }); trackCreatedUser(user.id, "test@example.com"); // For cleanup ``` -------------------------------- ### Optional Clerk Environment Variables Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/README.md Configure optional environment variables to customize Clerk's behavior, such as sign-in/sign-up URLs and the application port. ```bash NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in # Default: /sign-in NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up # Default: /sign-up PORT=3000 # Default: 3000 ``` -------------------------------- ### Create User Profile Page Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/INTEGRATION_GUIDE.md Implement a user profile page that fetches and displays user information. Redirects to sign-in if the user is not authenticated. Requires the 'auth' and 'currentUser' functions from Clerk. ```typescript //app/profile/page.tsx import { auth, currentUser } from "@clerk/nextjs/server"; import { redirect } from "next/navigation"; export default async function ProfilePage() { const { userId } = await auth(); if (!userId) { redirect("/sign-in"); } const user = await currentUser(); return (

Profile

Email: {user?.emailAddresses[0]?.emailAddress}

Name: {user?.firstName} {user?.lastName}

); } ``` -------------------------------- ### test.describe.configure() Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/api-reference/playwright-test.md Controls whether tests in a block run one-at-a-time (serial) or concurrently (parallel). Serial mode is useful for setup/teardown tests where order matters. ```APIDOC ## test.describe.configure() ### Description Controls whether tests in a block run one-at-a-time (serial) or concurrently (parallel). Serial mode is useful for setup/teardown tests where order matters. ### Options - **mode** (string) - Required - Either "serial" or "parallel". - "serial": Tests run sequentially (one after another). - "parallel": Tests run concurrently (default). ### Example ```typescript test.describe.configure({ mode: "serial" }); test("setup", async () => { // Runs first }); test("use setup result", async () => { // Runs second, after setup completes }); ``` ``` -------------------------------- ### Verify Middleware for Protected Routes Source: https://github.com/clerk/clerk-playwright-nextjs/blob/main/_autodocs/INTEGRATION_GUIDE.md Check if your proxy.ts (or middleware.ts) file exists and is correctly configured to protect routes. If missing, create it with the necessary route protection logic. ```bash # Check that proxy.ts exists (or middleware.ts) ls -la proxy.ts # If missing, create it with route protection ```