or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication-providers.mdcore-authentication.mddatabase-integration.mdindex.mdjwt-management.mdmiddleware-protection.mdreact-integration.mdserver-side-sessions.md

react-integration.mddocs/

0

# React Client Integration

1

2

React hooks and components for managing authentication state and user interactions in client-side components. Provides seamless integration with React applications for sign-in/sign-out flows and session management.

3

4

## Capabilities

5

6

### Session Provider

7

8

React context provider that makes session data available throughout the component tree and manages session state synchronization.

9

10

```typescript { .api }

11

/**

12

* Provider component that wraps the app to make session data globally available

13

* @param props - Configuration options for session management

14

* @returns JSX provider component

15

*/

16

function SessionProvider(props: SessionProviderProps): JSX.Element;

17

18

interface SessionProviderProps {

19

/** React children components */

20

children: React.ReactNode;

21

/** Optional initial session (from getServerSideProps) */

22

session?: Session | null;

23

/** Base URL for NextAuth.js API (auto-detected if not provided) */

24

baseUrl?: string;

25

/** Base path for NextAuth.js API routes (default: "/api/auth") */

26

basePath?: string;

27

/** Refetch session interval in seconds (0 to disable) */

28

refetchInterval?: number;

29

/** Refetch session when window gains focus (default: true) */

30

refetchOnWindowFocus?: boolean;

31

/** Refetch session when offline (default: true) */

32

refetchWhenOffline?: false;

33

}

34

```

35

36

**Usage Example:**

37

38

```typescript

39

// pages/_app.tsx (Pages Router)

40

import { SessionProvider } from "next-auth/react";

41

import type { AppProps } from "next/app";

42

43

export default function App({

44

Component,

45

pageProps: { session, ...pageProps },

46

}: AppProps) {

47

return (

48

<SessionProvider session={session}>

49

<Component {...pageProps} />

50

</SessionProvider>

51

);

52

}

53

54

// app/layout.tsx (App Router)

55

import { SessionProvider } from "next-auth/react";

56

57

export default function RootLayout({

58

children,

59

}: {

60

children: React.ReactNode;

61

}) {

62

return (

63

<html lang="en">

64

<body>

65

<SessionProvider>

66

{children}

67

</SessionProvider>

68

</body>

69

</html>

70

);

71

}

72

```

73

74

### Use Session Hook

75

76

React hook that provides access to the current user session and loading state.

77

78

```typescript { .api }

79

/**

80

* React hook for accessing session data and authentication state

81

* @param options - Hook configuration options

82

* @returns Session context value with data, status and update function

83

*/

84

function useSession<R extends boolean>(

85

options?: UseSessionOptions<R>

86

): SessionContextValue<R>;

87

88

interface UseSessionOptions<R extends boolean> {

89

/** Redirect to sign-in page if user is not authenticated */

90

required?: R;

91

/** Custom callback when user is unauthenticated (prevents automatic redirect) */

92

onUnauthenticated?: () => void;

93

}

94

95

type SessionContextValue<R extends boolean = false> = R extends true

96

?

97

| { update: UpdateSession; data: Session; status: "authenticated" }

98

| { update: UpdateSession; data: null; status: "loading" }

99

:

100

| { update: UpdateSession; data: Session; status: "authenticated" }

101

| {

102

update: UpdateSession;

103

data: null;

104

status: "unauthenticated" | "loading";

105

};

106

107

type UpdateSession = (data?: any) => Promise<Session | null>;

108

```

109

110

**Usage Examples:**

111

112

```typescript

113

// Basic usage

114

import { useSession } from "next-auth/react";

115

116

export default function Component() {

117

const { data: session, status } = useSession();

118

119

if (status === "loading") return <p>Loading...</p>;

120

121

if (status === "unauthenticated") return <p>Access Denied</p>;

122

123

return (

124

<>

125

<h1>Protected Page</h1>

126

<p>You can view this page because you are signed in.</p>

127

<p>Welcome {session.user?.name}</p>

128

</>

129

);

130

}

131

132

// Required authentication with redirect

133

export default function ProtectedComponent() {

134

const { data: session } = useSession({ required: true });

135

136

// This will automatically redirect to sign-in if not authenticated

137

return <p>Welcome {session?.user?.name}</p>;

138

}

139

140

// Custom unauthenticated handler

141

export default function ConditionalComponent() {

142

const { data: session, status } = useSession({

143

required: false,

144

onUnauthenticated: () => {

145

// Custom handling instead of redirect

146

console.log("User not authenticated");

147

},

148

});

149

150

return (

151

<div>

152

{session ? (

153

<UserContent user={session.user} />

154

) : (

155

<GuestContent />

156

)}

157

</div>

158

);

159

}

160

```

161

162

### Sign In Function

163

164

Client-side function to initiate authentication flow with support for multiple providers and custom options.

165

166

```typescript { .api }

167

/**

168

* Initiate sign-in flow or redirect to sign-in page

169

* @param provider - Authentication provider ID or undefined for provider selection

170

* @param options - Sign-in configuration options

171

* @param authorizationParams - Additional OAuth authorization parameters

172

* @returns Promise with sign-in result (for credentials/email providers)

173

*/

174

function signIn<P extends RedirectableProviderType | undefined = undefined>(

175

provider?: LiteralUnion<

176

P extends RedirectableProviderType

177

? P | BuiltInProviderType

178

: BuiltInProviderType

179

>,

180

options?: SignInOptions,

181

authorizationParams?: SignInAuthorizationParams

182

): Promise<

183

P extends RedirectableProviderType ? SignInResponse | undefined : undefined

184

>;

185

186

interface SignInOptions {

187

/** URL to redirect to after successful sign-in */

188

callbackUrl?: string;

189

/** Whether to redirect after sign-in (default: true) */

190

redirect?: boolean;

191

/** Additional form data for credentials provider */

192

[key: string]: any;

193

}

194

195

interface SignInAuthorizationParams {

196

/** Additional OAuth authorization parameters */

197

[key: string]: string;

198

}

199

200

interface SignInResponse {

201

/** Error message if sign-in failed */

202

error: string | undefined;

203

/** HTTP status code */

204

status: number;

205

/** Whether sign-in was successful */

206

ok: boolean;

207

/** URL user was redirected to (null if error) */

208

url: string | null;

209

}

210

211

type RedirectableProviderType = "email" | "credentials";

212

type BuiltInProviderType = RedirectableProviderType | OAuthProviderType;

213

```

214

215

**Usage Examples:**

216

217

```typescript

218

import { signIn } from "next-auth/react";

219

220

// Sign in with OAuth provider (redirects to provider)

221

function LoginButton() {

222

return (

223

<button onClick={() => signIn("google")}>

224

Sign in with Google

225

</button>

226

);

227

}

228

229

// Sign in with custom callback URL

230

function CustomLoginButton() {

231

return (

232

<button

233

onClick={() => signIn("github", {

234

callbackUrl: "/dashboard"

235

})}

236

>

237

Sign in with GitHub

238

</button>

239

);

240

}

241

242

// Sign in with credentials (no redirect)

243

async function handleCredentialsLogin(email: string, password: string) {

244

const result = await signIn("credentials", {

245

email,

246

password,

247

redirect: false,

248

});

249

250

if (result?.error) {

251

console.error("Sign in failed:", result.error);

252

} else {

253

console.log("Sign in successful");

254

}

255

}

256

257

// Generic sign-in (shows provider selection page)

258

function SignInButton() {

259

return (

260

<button onClick={() => signIn()}>

261

Sign in

262

</button>

263

);

264

}

265

```

266

267

### Sign Out Function

268

269

Client-side function to sign out the current user with customizable redirect behavior.

270

271

```typescript { .api }

272

/**

273

* Sign out the current user

274

* @param options - Sign-out configuration options

275

* @returns Promise with sign-out result (if redirect is disabled)

276

*/

277

function signOut<R extends boolean = true>(

278

options?: SignOutParams<R>

279

): Promise<R extends true ? undefined : SignOutResponse>;

280

281

interface SignOutParams<R extends boolean = true> {

282

/** URL to redirect to after sign-out */

283

callbackUrl?: string;

284

/** Whether to redirect after sign-out (default: true) */

285

redirect?: R;

286

}

287

288

interface SignOutResponse {

289

/** URL user was redirected to */

290

url: string;

291

}

292

```

293

294

**Usage Examples:**

295

296

```typescript

297

import { signOut } from "next-auth/react";

298

299

// Basic sign out (redirects to home page)

300

function SignOutButton() {

301

return (

302

<button onClick={() => signOut()}>

303

Sign out

304

</button>

305

);

306

}

307

308

// Sign out with custom redirect

309

function CustomSignOutButton() {

310

return (

311

<button onClick={() => signOut({ callbackUrl: "/goodbye" })}>

312

Sign out

313

</button>

314

);

315

}

316

317

// Sign out without redirect

318

async function handleSignOut() {

319

const data = await signOut({ redirect: false });

320

console.log("Signed out, redirect URL:", data.url);

321

// Handle custom post-signout logic

322

}

323

```

324

325

### Get Session Function

326

327

Client-side function to manually fetch the current session (typically not needed when using useSession).

328

329

```typescript { .api }

330

/**

331

* Manually fetch session data on the client side

332

* @param params - Request context and options

333

* @returns Promise resolving to session object or null

334

*/

335

function getSession(params?: GetSessionParams): Promise<Session | null>;

336

337

interface GetSessionParams extends CtxOrReq {

338

/** Event that triggered session fetch */

339

event?: "storage" | "timer" | "hidden" | string;

340

/** Whether to trigger session sync event */

341

triggerEvent?: boolean;

342

/** Whether to broadcast session change to other tabs */

343

broadcast?: boolean;

344

}

345

346

interface CtxOrReq {

347

/** Request object (for SSR contexts) */

348

req?: Partial<IncomingMessage> & { body?: any };

349

/** App context containing request object */

350

ctx?: { req: Partial<IncomingMessage> & { body?: any } };

351

}

352

```

353

354

**Usage Example:**

355

356

```typescript

357

import { getSession } from "next-auth/react";

358

359

// Manually refresh session

360

async function refreshSession() {

361

const session = await getSession();

362

console.log("Current session:", session);

363

}

364

365

// Get session in event handler

366

async function handleButtonClick() {

367

const session = await getSession();

368

if (session) {

369

// Perform authenticated action

370

}

371

}

372

```

373

374

### Get CSRF Token

375

376

Function to retrieve the current CSRF token for custom form submissions.

377

378

```typescript { .api }

379

/**

380

* Get the current CSRF token for POST requests

381

* @param params - Request context

382

* @returns Promise resolving to CSRF token string

383

*/

384

function getCsrfToken(params?: CtxOrReq): Promise<string | undefined>;

385

```

386

387

**Usage Example:**

388

389

```typescript

390

import { getCsrfToken } from "next-auth/react";

391

392

// Custom form with CSRF protection

393

export default function CustomForm() {

394

const [csrfToken, setCsrfToken] = useState("");

395

396

useEffect(() => {

397

getCsrfToken().then(token => setCsrfToken(token || ""));

398

}, []);

399

400

return (

401

<form method="post" action="/api/auth/callback/credentials">

402

<input name="csrfToken" type="hidden" value={csrfToken} />

403

<input name="email" type="email" required />

404

<input name="password" type="password" required />

405

<button type="submit">Sign in</button>

406

</form>

407

);

408

}

409

```

410

411

### Get Providers

412

413

Function to retrieve the list of configured authentication providers.

414

415

```typescript { .api }

416

/**

417

* Get list of configured authentication providers

418

* @returns Promise resolving to provider configuration object

419

*/

420

function getProviders(): Promise<

421

Record<LiteralUnion<BuiltInProviderType>, ClientSafeProvider> | null

422

>;

423

424

interface ClientSafeProvider {

425

/** Provider ID */

426

id: string;

427

/** Provider display name */

428

name: string;

429

/** Provider type */

430

type: string;

431

/** Sign-in URL */

432

signinUrl: string;

433

/** Callback URL */

434

callbackUrl: string;

435

}

436

```

437

438

**Usage Example:**

439

440

```typescript

441

import { getProviders, signIn } from "next-auth/react";

442

443

export default function SignIn() {

444

const [providers, setProviders] = useState<Record<string, ClientSafeProvider> | null>(null);

445

446

useEffect(() => {

447

getProviders().then(setProviders);

448

}, []);

449

450

return (

451

<div>

452

{providers &&

453

Object.values(providers).map((provider) => (

454

<div key={provider.name}>

455

<button onClick={() => signIn(provider.id)}>

456

Sign in with {provider.name}

457

</button>

458

</div>

459

))}

460

</div>

461

);

462

}

463

```

464

465

### Session Context

466

467

React context for accessing session data directly (typically used internally by useSession).

468

469

```typescript { .api }

470

/**

471

* React context for session data

472

*/

473

const SessionContext: React.Context<SessionContextValue | undefined>;

474

475

interface SessionContextValue<R extends boolean = false> {

476

/** Session data (null if not authenticated) */

477

data: Session | null;

478

/** Session status */

479

status: "loading" | "authenticated" | "unauthenticated";

480

/** Function to update session data */

481

update: UpdateSession;

482

}

483

```

484

485

## Session State Management

486

487

### Session Status States

488

489

```typescript { .api }

490

type SessionStatus = "loading" | "authenticated" | "unauthenticated";

491

492

interface SessionState {

493

/** Current session status */

494

status: SessionStatus;

495

/** Session data when authenticated */

496

data: Session | null;

497

/** Last sync timestamp */

498

lastSync: number;

499

/** Whether session is being fetched */

500

loading: boolean;

501

}

502

```

503

504

### Session Update Patterns

505

506

```typescript { .api }

507

/**

508

* Session update function signature

509

*/

510

type UpdateSession = (data?: any) => Promise<Session | null>;

511

512

interface SessionUpdateOptions {

513

/** New session data to merge */

514

data?: any;

515

/** Whether to broadcast update to other tabs */

516

broadcast?: boolean;

517

/** Custom event type for update */

518

event?: string;

519

}

520

```

521

522

**Usage Examples:**

523

524

```typescript

525

// Update session with new data

526

const { data: session, update } = useSession();

527

528

async function updateProfile(newProfile: any) {

529

// Update session with new profile data

530

await update({

531

...session,

532

user: {

533

...session?.user,

534

...newProfile,

535

},

536

});

537

}

538

539

// Trigger session refresh

540

async function refreshUserData() {

541

await update(); // Refetch session from server

542

}

543

```

544

545

## Types

546

547

### React-Specific Types

548

549

```typescript { .api }

550

interface SessionProviderProps {

551

children: React.ReactNode;

552

session?: Session | null;

553

baseUrl?: string;

554

basePath?: string;

555

refetchInterval?: number;

556

refetchOnWindowFocus?: boolean;

557

refetchWhenOffline?: false;

558

}

559

560

interface UseSessionOptions<R extends boolean> {

561

required?: R;

562

onUnauthenticated?: () => void;

563

}

564

565

type LiteralUnion<T extends U, U = string> = T | (U & Record<never, never>);

566

567

type OAuthProviderType =

568

| "42-school" | "apple" | "atlassian" | "auth0" | "authentik"

569

| "azure-ad-b2c" | "azure-ad" | "battlenet" | "box" | "boxyhq-saml"

570

| "cognito" | "coinbase" | "discord" | "dribbble" | "dropbox"

571

| "duende-identity-server6" | "eveonline" | "facebook" | "faceit"

572

| "foursquare" | "freshbooks" | "fusionauth" | "github" | "gitlab"

573

| "google" | "hubspot" | "identity-server4" | "instagram" | "kakao"

574

| "keycloak" | "line" | "linkedin" | "mailchimp" | "mailru" | "medium"

575

| "netlify" | "notion" | "oauth" | "okta" | "onelogin" | "osso"

576

| "patreon" | "pinterest" | "pipedrive" | "reddit" | "salesforce"

577

| "slack" | "spotify" | "strava" | "todoist" | "trakt" | "twitch"

578

| "twitter" | "united-effects" | "vk" | "wikimedia" | "wordpress"

579

| "workos" | "yandex" | "zitadel" | "zoho" | "zoom";

580

```