### Install Playwright Browsers for E2E Tests (Bash)
Source: https://github.com/clerk/clerk-multidomain-demo/blob/main/README.md
Install the necessary Playwright browser binaries required for running E2E tests. This command resolves 'Executable doesn't exist' errors by downloading the specified browser executables.
```bash
# Install browsers for all e2e test suites
pnpm e2e:install:browsers
```
--------------------------------
### Integrate React-Specific ESLint Plugins
Source: https://github.com/clerk/clerk-multidomain-demo/blob/main/apps/react/root-domain/README.md
This code example demonstrates how to integrate `eslint-plugin-react-x` and `eslint-plugin-react-dom` into your ESLint configuration. It enables recommended lint rules specifically for React and React DOM components, enhancing code quality for React projects.
```javascript
// eslint.config.js
import reactX from "eslint-plugin-react-x";
import reactDom from "eslint-plugin-react-dom";
export default tseslint.config([
globalIgnores(["dist"]),
{
files: ["**/*.{ts,tsx}"],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs["recommended-typescript"],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ["./tsconfig.node.json", "./tsconfig.app.json"],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
]);
```
--------------------------------
### Monorepo Development Commands (Turborepo)
Source: https://context7.com/clerk/clerk-multidomain-demo/llms.txt
Provides essential Turborepo commands for monorepo development. These commands facilitate dependency installation, running development servers for multiple applications, building, linting, type checking, and formatting across the project.
```bash
# Install dependencies for all applications
pnpm install
# Run all applications (Next.js root, Next.js satellite, React root, React satellite)
pnpm dev
# Run only Next.js applications (ports 3000 and 3001)
pnpm dev:nextjs
# Run only React applications (ports 3002 and 3003)
pnpm dev:react
# Build all applications
pnpm build
# Run linting across all projects
pnpm lint
# Type check all projects
pnpm check-types
# Format all TypeScript and markdown files
pnpm format
```
--------------------------------
### Configure ClerkProvider for Root Domain (Next.js)
Source: https://context7.com/clerk/clerk-multidomain-demo/llms.txt
Configures the ClerkProvider for the root domain, enabling cross-domain authentication by specifying allowed redirect origins. This setup handles all primary authentication flows and redirects.
```tsx
import { ClerkProvider, UserButton, SignedIn } from "@clerk/nextjs";
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
{children}
);
}
```
--------------------------------
### Configure Type-Aware ESLint Rules in TypeScript
Source: https://github.com/clerk/clerk-multidomain-demo/blob/main/apps/react/root-domain/README.md
This snippet shows how to configure ESLint to enable type-aware lint rules for TypeScript files. It involves extending ESLint configurations with specific type-checked rule sets and setting up project parsing options.
```javascript
export default tseslint.config([
globalIgnores(["dist"]),
{
files: ["**/*.{ts,tsx}"],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
...tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
...tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
...tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ["./tsconfig.node.json", "./tsconfig.app.json"],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
]);
```
--------------------------------
### Playwright Configuration for Multi-Domain Testing
Source: https://context7.com/clerk/clerk-multidomain-demo/llms.txt
This TypeScript code configures Playwright for multi-domain testing, allowing simultaneous testing of root and satellite domains. It specifies the test directory, output directory, and configures web servers for both the root and satellite domains, reusing existing servers when not in a CI environment. It also defines Playwright projects, including a global setup and configurations for different browser profiles, with specific handling for authenticated tests using storage state.
```typescript
import { defineConfig, devices } from "@playwright/test";
import path from "path";
const PORT = process.env.PORT || 3000;
const ROOT_URL = process.env.NEXT_PUBLIC_ROOT_DOMAIN_URL || `http://localhost:${PORT}`;
const SATELLITE_URL = process.env.NEXT_PUBLIC_SATELLITE_DOMAIN_URL || "http://localhost:3001";
export default defineConfig({
testDir: path.join(__dirname, "e2e"),
outputDir: "test-results/",
webServer: [
{
command: "pnpm dev",
url: ROOT_URL,
reuseExistingServer: !process.env.CI,
},
{
command: "pnpm dev",
url: SATELLITE_URL,
reuseExistingServer: !process.env.CI,
cwd: path.join(__dirname, "../satellite-domain"),
},
],
use: {
baseURL: ROOT_URL,
trace: "retry-with-trace",
},
projects: [
{
name: "global setup",
testMatch: /global\.setup\.ts/,
},
{
name: "chromium",
use: { ...devices["Desktop Chrome"] },
testIgnore: /.*authenticated\.spec\.ts/,
dependencies: ["global setup"],
},
{
name: "chromium-authenticated",
use: {
...devices["Desktop Chrome"],
storageState: "playwright/.clerk/user.json",
},
testMatch: /.*authenticated\.spec\.ts/,
dependencies: ["global setup"],
},
],
});
```
--------------------------------
### Run Specific Framework E2E Tests (Bash)
Source: https://github.com/clerk/clerk-multidomain-demo/blob/main/README.md
Execute E2E tests tailored for different front-end frameworks. These commands initiate the testing process for either Next.js or React applications, ensuring cross-domain authentication flows are validated.
```bash
# Run Next.js e2e tests only
pnpm e2e:nextjs
```
```bash
# Run React e2e tests only
pnpm e2e:react
```
--------------------------------
### Environment Configuration for Satellite Domain (Next.js)
Source: https://context7.com/clerk/clerk-multidomain-demo/llms.txt
Configures environment variables for a satellite domain, ensuring it correctly points back to the root domain for authentication-related operations. This includes essential Clerk keys.
```bash
# Satellite Domain Environment Variables (.env)
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_REST_OF_YOUR_KEY_HERE
CLERK_SECRET_KEY=sk_test_REST_OF_YOUR_KEY_HERE
```
--------------------------------
### Environment Configuration for Root Domain (Next.js)
Source: https://context7.com/clerk/clerk-multidomain-demo/llms.txt
Sets up essential environment variables for the root domain to facilitate cross-domain authentication. Crucially, it defines `NEXT_PUBLIC_ALLOWED_REDIRECT_ORIGINS` to include all satellite domains.
```bash
# Root Domain Environment Variables (.env)
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_REST_OF_YOUR_KEY_HERE
CLERK_SECRET_KEY=sk_test_REST_OF_YOUR_KEY_HERE
# Sign-in URL path on root domain
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
# Comma-separated list of allowed satellite domains
# Development: localhost ports
# Production: full domain URLs (e.g., https://satellite.example.com)
NEXT_PUBLIC_ALLOWED_REDIRECT_ORIGINS="http://localhost:3001"
# Satellite domain URL for linking
NEXT_PUBLIC_SATELLITE_DOMAIN_URL=http://localhost:3001
# E2E testing credentials
E2E_CLERK_USER_PASSWORD=your_test_password
E2E_CLERK_USER_EMAIL=test@example.com
E2E_CLERK_USER_USERNAME=testuser
```
--------------------------------
### Configure ClerkProvider for Satellite Domain (Next.js)
Source: https://context7.com/clerk/clerk-multidomain-demo/llms.txt
Configures the ClerkProvider for a satellite domain, which reads authentication state from the root domain. Redirect origins are not specified here as it relies on the root domain for authentication.
```tsx
import { ClerkProvider, UserButton, SignedIn } from "@clerk/nextjs";
export default async function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
{children}
);
}
```
--------------------------------
### ClerkProvider Configuration for Satellite Domain (React)
Source: https://context7.com/clerk/clerk-multidomain-demo/llms.txt
Sets up the ClerkProvider for a satellite domain in a React application. It requires the publishable key, sign-in URL, the satellite domain identifier, and the isSatellite flag. Dependencies include @clerk/clerk-react and react-router-dom.
```tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { ClerkProvider } from "@clerk/clerk-react";
import App from "./App.tsx";
const publishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY;
if (!publishableKey) {
throw new Error("Missing Publishable Key");
}
createRoot(document.getElementById("root")!).render(
,
);
```
--------------------------------
### Set Environment Variables for E2E Tests (Bash)
Source: https://github.com/clerk/clerk-multidomain-demo/blob/main/README.md
Configure necessary environment variables for authentication during E2E tests. These variables store the test user's credentials, which are essential for the testing framework to simulate user sessions.
```bash
E2E_CLERK_USER_USERNAME=your-test-user-username
E2E_CLERK_USER_EMAIL=your-test-user-email
E2E_CLERK_USER_PASSWORD=your-test-user-password
```
--------------------------------
### Implement Next.js Middleware for Route Protection
Source: https://context7.com/clerk/clerk-multidomain-demo/llms.txt
Utilizes Clerk middleware to protect routes on both root and satellite domains. It defines public routes and enforces authentication for protected routes, redirecting unauthenticated users to sign-in flows.
```typescript
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
const isPublicRoute = createRouteMatcher(["/sign-in(.*)", "/", "/test"]);
export default clerkMiddleware(async (auth, request) => {
if (!isPublicRoute(request)) {
await auth.protect();
}
});
export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
"/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
// Always run for API routes
"/(api|trpc)(.*)",
],
};
```
--------------------------------
### Conditional Navigation with Clerk and Next.js
Source: https://context7.com/clerk/clerk-multidomain-demo/llms.txt
This React component dynamically renders navigation links based on user authentication status and the current route. It uses Clerk's `SignedIn` and `SignedOut` components for auth state and Next.js's `usePathname` hook to determine the current path. Dependencies include `@clerk/nextjs` for authentication and `@repo/ui/button` for UI elements.
```tsx
"use client";
import { SignInButton, SignedIn, SignedOut } from "@clerk/nextjs";
import { Button } from "@repo/ui/button";
import Link from "next/link";
import { usePathname } from "next/navigation";
export const NavbarLinks = () => {
const path = usePathname();
return (
<>
{path === "/" && (
)}
{path !== "/" && (
)}
>
);
};
```
--------------------------------
### ClerkProvider Configuration for Root Domain (React)
Source: https://context7.com/clerk/clerk-multidomain-demo/llms.txt
Configures the ClerkProvider for the root domain in a React application. It requires a publishable key, allowed redirect origins, and the sign-in URL. Dependencies include @clerk/clerk-react and react-router-dom.
```tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BrowserRouter } from "react-router-dom";
import { ClerkProvider } from "@clerk/clerk-react";
import App from "./App.tsx";
const publishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY;
if (!publishableKey) {
throw new Error("Missing Publishable Key");
}
createRoot(document.getElementById("root")!).render(
,
);
```
--------------------------------
### End-to-End Multi-Domain Authentication Test with Playwright
Source: https://context7.com/clerk/clerk-multidomain-demo/llms.txt
This TypeScript code snippet sets up and executes an end-to-end test for a multi-domain authentication flow using Clerk and Playwright. It configures testing tokens, signs out existing users, and then tests the sign-in process on a satellite domain, verifying redirection to the root domain for authentication and back to the satellite domain upon successful sign-in. Environment variables for domain URLs and user credentials are required.
```typescript
import { clerk, setupClerkTestingToken } from "@clerk/testing/playwright";
import { test, expect, Page } from "@playwright/test";
const satelliteUrl = process.env.NEXT_PUBLIC_SATELLITE_DOMAIN_URL || "http://localhost:3001";
const rootUrl = process.env.NEXT_PUBLIC_ROOT_DOMAIN_URL || "http://localhost:3000";
test.describe("Multi-domain authentication flow", () => {
test.beforeEach(async ({ page }) => {
await setupClerkTestingToken({ page });
await clerk.signOut({ page });
});
test("sign in on satellite redirects to root domain and back", async ({ page }) => {
await page.goto(satelliteUrl);
await page.getByRole("button", { name: "Sign In" }).click();
// Should redirect to root domain sign-in
await page.waitForURL(new RegExp(`${rootUrl}/sign-in`));
await expect(page.locator(".cl-signIn-root").first()).toBeVisible();
// Complete sign-in
await page.locator("input[name=identifier]").fill(process.env.E2E_CLERK_USER_EMAIL!)
await page.getByRole("button", { name: "Continue", exact: true }).click();
await page.locator("input[name=password]").fill(process.env.E2E_CLERK_USER_PASSWORD!)
await page.getByRole("button", { name: "Continue", exact: true }).click();
// Should return to satellite domain
await page.waitForURL(new RegExp(`${satelliteUrl}/`));
expect(new URL(page.url()).origin).toBe(satelliteUrl);
});
});
// Run tests with:
// pnpm e2e:nextjs # Test Next.js apps
// pnpm e2e:react # Test React apps
// pnpm e2e:install:browsers # Install Playwright browsers
```
--------------------------------
### Environment Validation with Zod (React)
Source: https://context7.com/clerk/clerk-multidomain-demo/llms.txt
Validates environment variables for React applications using Zod and @t3-oss/env-core. It defines client-side variables with type constraints, ensuring type safety. Dependencies include zod and @t3-oss/env-core.
```typescript
import { createEnv } from "@t3-oss/env-core";
import { z } from "zod";
export const env = createEnv({
clientPrefix: "VITE_",
client: {
VITE_CLERK_PUBLISHABLE_KEY: z.string().min(1),
VITE_ALLOWED_REDIRECT_ORIGINS: z.string().min(1),
VITE_CLERK_SIGN_IN_URL: z.string().min(1),
VITE_SATELLITE_DOMAIN_URL: z.string().min(1),
},
runtimeEnv: import.meta.env,
});
// Usage in application
const publishableKey = env.VITE_CLERK_PUBLISHABLE_KEY;
const allowedOrigins = env.VITE_ALLOWED_REDIRECT_ORIGINS.split(",");
```
--------------------------------
### Protected Route Component for React Authentication
Source: https://context7.com/clerk/clerk-multidomain-demo/llms.txt
Implements a reusable ProtectedRoute component in React to manage authentication state. It checks if the user is loaded and signed in, rendering children if authenticated or redirecting to sign-in otherwise. Uses hooks from @clerk/clerk-react.
```tsx
import { RedirectToSignIn, useAuth } from "@clerk/clerk-react";
interface ProtectedRouteProps {
children: React.ReactNode;
}
export function ProtectedRoute({ children }: ProtectedRouteProps) {
const { isSignedIn, isLoaded } = useAuth();
if (!isLoaded) {
return
Loading...
;
}
if (!isSignedIn) {
return ;
}
return <>{children}>;
}
// Usage in App.tsx
import { Routes, Route } from "react-router-dom";
import DashboardPage from "./pages/DashboardPage";
function App() {
return (
} />
}
/>
} />
);
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.