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

index.mddocs/

0

# NextAuth.js

1

2

NextAuth.js is a comprehensive authentication library for Next.js applications that provides flexible OAuth integration, email/passwordless authentication, and credentials-based authentication. It supports both JSON Web Token and database session management, is designed for serverless environments, and emphasizes security by default with features like CSRF protection and encrypted JWTs.

3

4

## Package Information

5

6

- **Package Name**: next-auth

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install next-auth`

10

11

## Core Imports

12

13

```typescript

14

import NextAuth from "next-auth";

15

import { getServerSession } from "next-auth/next";

16

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

17

import { getToken } from "next-auth/jwt";

18

import { withAuth } from "next-auth/middleware";

19

```

20

21

For CommonJS:

22

```javascript

23

const NextAuth = require("next-auth").default;

24

const { getServerSession } = require("next-auth/next");

25

const { useSession, signIn, signOut } = require("next-auth/react");

26

```

27

28

## Basic Usage

29

30

```typescript

31

// Configure NextAuth.js (pages/api/auth/[...nextauth].ts)

32

import NextAuth from "next-auth";

33

import GoogleProvider from "next-auth/providers/google";

34

35

export default NextAuth({

36

providers: [

37

GoogleProvider({

38

clientId: process.env.GOOGLE_CLIENT_ID!,

39

clientSecret: process.env.GOOGLE_CLIENT_SECRET!,

40

}),

41

],

42

callbacks: {

43

async session({ session, token }) {

44

session.user.id = token.sub;

45

return session;

46

},

47

},

48

});

49

50

// Use in React components

51

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

52

53

export default function Component() {

54

const { data: session } = useSession();

55

56

if (session) {

57

return (

58

<>

59

<p>Signed in as {session.user?.email}</p>

60

<button onClick={() => signOut()}>Sign out</button>

61

</>

62

);

63

}

64

return (

65

<>

66

<p>Not signed in</p>

67

<button onClick={() => signIn()}>Sign in</button>

68

</>

69

);

70

}

71

```

72

73

## Architecture

74

75

NextAuth.js is built around several key components:

76

77

- **Core Authentication**: Main `NextAuth` function for configuration and request handling

78

- **Session Management**: Support for both JWT and database sessions with flexible lifecycle callbacks

79

- **Provider System**: Extensive built-in support for 67+ OAuth providers plus email and credentials authentication

80

- **Client Library**: React hooks and functions for client-side authentication state management

81

- **Server Integration**: Server-side session retrieval and JWT utilities for API routes and SSR

82

- **Middleware**: Route protection and authorization for Next.js middleware

83

- **Adapter Pattern**: Database integration through adapters for any database backend

84

- **Security**: Built-in CSRF protection, encrypted JWTs (JWE), automatic key generation, and secure cookies

85

86

## Capabilities

87

88

### Core Authentication Configuration

89

90

Main NextAuth configuration and request handling functionality. The central component for setting up authentication providers, callbacks, and session management.

91

92

```typescript { .api }

93

function NextAuth(options: AuthOptions): any;

94

function NextAuth(req: NextApiRequest, res: NextApiResponse, options: AuthOptions): any;

95

function NextAuth(req: NextRequest, res: RouteHandlerContext, options: AuthOptions): any;

96

97

interface AuthOptions {

98

providers: Provider[];

99

secret?: string;

100

session?: Partial<SessionOptions>;

101

jwt?: Partial<JWTOptions>;

102

pages?: Partial<PagesOptions>;

103

callbacks?: Partial<CallbacksOptions>;

104

events?: Partial<EventCallbacks>;

105

adapter?: Adapter;

106

debug?: boolean;

107

logger?: Partial<LoggerInstance>;

108

theme?: Theme;

109

useSecureCookies?: boolean;

110

cookies?: Partial<CookiesOptions>;

111

}

112

```

113

114

[Core Authentication](./core-authentication.md)

115

116

### Server-Side Session Management

117

118

Server-side utilities for retrieving and managing user sessions in API routes, server components, and getServerSideProps.

119

120

```typescript { .api }

121

function getServerSession<O extends GetServerSessionOptions, R = any>(

122

...args: GetServerSessionParams<O>

123

): Promise<R | null>;

124

125

interface Session extends DefaultSession {

126

user?: {

127

name?: string | null;

128

email?: string | null;

129

image?: string | null;

130

};

131

expires: ISODateString;

132

}

133

```

134

135

[Server-Side Sessions](./server-side-sessions.md)

136

137

### React Client Integration

138

139

React hooks and components for managing authentication state and user interactions in client-side components.

140

141

```typescript { .api }

142

function useSession<R extends boolean>(

143

options?: UseSessionOptions<R>

144

): SessionContextValue<R>;

145

146

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

147

148

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

149

provider?: LiteralUnion<P extends RedirectableProviderType ? P | BuiltInProviderType : BuiltInProviderType>,

150

options?: SignInOptions,

151

authorizationParams?: SignInAuthorizationParams

152

): Promise<P extends RedirectableProviderType ? SignInResponse | undefined : undefined>;

153

154

function signOut<R extends boolean = true>(

155

options?: SignOutParams<R>

156

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

157

```

158

159

[React Integration](./react-integration.md)

160

161

### JWT Token Management

162

163

JWT utilities for encoding, decoding, and extracting tokens from requests. Essential for API authentication and custom session handling.

164

165

```typescript { .api }

166

function encode(params: JWTEncodeParams): Promise<string>;

167

function decode(params: JWTDecodeParams): Promise<JWT | null>;

168

function getToken<R extends boolean = false>(

169

params: GetTokenParams<R>

170

): Promise<R extends true ? string : JWT | null>;

171

172

interface JWT extends Record<string, unknown>, DefaultJWT {

173

name?: string | null;

174

email?: string | null;

175

picture?: string | null;

176

sub?: string;

177

}

178

```

179

180

[JWT Management](./jwt-management.md)

181

182

### Middleware and Route Protection

183

184

Middleware functions for protecting routes and implementing authorization logic in Next.js applications.

185

186

```typescript { .api }

187

function withAuth(): ReturnType<NextMiddlewareWithAuth>;

188

function withAuth(middleware: NextMiddlewareWithAuth): NextMiddlewareWithAuth;

189

function withAuth(options: NextAuthMiddlewareOptions): NextMiddlewareWithAuth;

190

191

interface NextAuthMiddlewareOptions {

192

pages?: AuthOptions["pages"];

193

cookies?: Partial<Record<keyof Pick<keyof AuthOptions["cookies"], "sessionToken">, Omit<CookieOption, "options">>>;

194

jwt?: Partial<Pick<JWTOptions, "decode">>;

195

callbacks?: {

196

authorized?: (params: { token: JWT | null; req: NextRequest }) => Awaitable<boolean>;

197

};

198

secret?: string;

199

}

200

```

201

202

[Middleware Protection](./middleware-protection.md)

203

204

### Authentication Providers

205

206

Built-in support for 67+ authentication providers including OAuth, email, and credentials-based authentication.

207

208

```typescript { .api }

209

interface Provider extends CommonProviderOptions {

210

id: string;

211

name: string;

212

type: ProviderType;

213

options?: any;

214

}

215

216

type ProviderType = "oauth" | "email" | "credentials";

217

218

// OAuth Provider Configuration

219

interface OAuthConfig<P> {

220

id: string;

221

name: string;

222

type: "oauth";

223

authorization: string | AuthorizationEndpointHandler;

224

token: string | TokenEndpointHandler;

225

userinfo?: string | UserinfoEndpointHandler;

226

client: Partial<ClientMetadata>;

227

clientId: string;

228

clientSecret: string;

229

}

230

```

231

232

[Authentication Providers](./authentication-providers.md)

233

234

### Database Integration

235

236

Adapter interface for integrating with any database backend, supporting user management, session storage, and account linking.

237

238

```typescript { .api }

239

interface Adapter {

240

createUser?: (user: Omit<AdapterUser, "id">) => Awaitable<AdapterUser>;

241

getUser?: (id: string) => Awaitable<AdapterUser | null>;

242

getUserByEmail?: (email: string) => Awaitable<AdapterUser | null>;

243

getUserByAccount?: (providerAccountId: Pick<AdapterAccount, "provider" | "providerAccountId">) => Awaitable<AdapterUser | null>;

244

updateUser?: (user: Partial<AdapterUser> & Pick<AdapterUser, "id">) => Awaitable<AdapterUser>;

245

linkAccount?: (account: AdapterAccount) => Promise<void> | Awaitable<AdapterAccount | null | undefined>;

246

createSession?: (session: { sessionToken: string; userId: string; expires: Date }) => Awaitable<AdapterSession>;

247

getSessionAndUser?: (sessionToken: string) => Awaitable<{ session: AdapterSession; user: AdapterUser } | null>;

248

updateSession?: (session: Partial<AdapterSession> & Pick<AdapterSession, "sessionToken">) => Awaitable<AdapterSession | null | undefined>;

249

deleteSession?: (sessionToken: string) => Promise<void> | Awaitable<AdapterSession | null | undefined>;

250

}

251

```

252

253

[Database Integration](./database-integration.md)

254

255

## Types

256

257

### Core Types

258

259

```typescript { .api }

260

type Awaitable<T> = T | PromiseLike<T>;

261

262

interface User extends DefaultUser {

263

id: string;

264

name?: string | null;

265

email?: string | null;

266

image?: string | null;

267

}

268

269

interface Account extends Partial<TokenSetParameters> {

270

providerAccountId: string;

271

userId?: string;

272

provider: string;

273

type: ProviderType;

274

}

275

276

interface Profile extends Record<string, any> {

277

sub?: string;

278

name?: string;

279

email?: string;

280

image?: string;

281

}

282

283

type ISODateString = string;

284

```

285

286

### Configuration Types

287

288

```typescript { .api }

289

interface SessionOptions {

290

strategy: "jwt" | "database";

291

maxAge: number;

292

updateAge: number;

293

generateSessionToken?: () => Awaitable<string>;

294

}

295

296

interface JWTOptions {

297

secret: string;

298

maxAge: number;

299

encode?: (params: JWTEncodeParams) => Awaitable<string>;

300

decode?: (params: JWTDecodeParams) => Awaitable<JWT | null>;

301

}

302

303

interface PagesOptions {

304

signIn?: string;

305

signOut?: string;

306

error?: string;

307

verifyRequest?: string;

308

newUser?: string;

309

}

310

```

311

312

### Callback Types

313

314

```typescript { .api }

315

interface CallbacksOptions<P = Profile, A = Account> {

316

signIn?: (params: {

317

user: User | AdapterUser;

318

account: A | null;

319

profile?: P;

320

email?: { verificationRequest?: boolean };

321

credentials?: Record<string, CredentialInput>;

322

}) => Awaitable<string | boolean>;

323

324

redirect?: (params: {

325

url: string;

326

baseUrl: string;

327

}) => Awaitable<string>;

328

329

session?: (params: {

330

session: Session;

331

token: JWT;

332

user: AdapterUser;

333

newSession?: any;

334

trigger?: "update";

335

}) => Awaitable<Session | DefaultSession>;

336

337

jwt?: (params: {

338

token: JWT;

339

user: User | AdapterUser;

340

account: A | null;

341

profile?: P;

342

trigger?: "signIn" | "signUp" | "update";

343

isNewUser?: boolean;

344

session?: any;

345

}) => Awaitable<JWT>;

346

}

347

```

348

349

### Event Callbacks

350

351

```typescript { .api }

352

interface EventCallbacks {

353

/** Called when a user successfully signs in */

354

signIn: (message: {

355

user: User;

356

account: Account | null;

357

profile?: Profile;

358

isNewUser?: boolean;

359

}) => Awaitable<void>;

360

361

/** Called when a user signs out */

362

signOut: (message: {

363

session: Session;

364

token: JWT;

365

}) => Awaitable<void>;

366

367

/** Called when a new user is created */

368

createUser: (message: { user: User }) => Awaitable<void>;

369

370

/** Called when a user is updated */

371

updateUser: (message: { user: User }) => Awaitable<void>;

372

373

/** Called when an account is linked to a user */

374

linkAccount: (message: {

375

user: User | AdapterUser;

376

account: Account;

377

profile: User | AdapterUser;

378

}) => Awaitable<void>;

379

380

/** Called when a session is accessed */

381

session: (message: {

382

session: Session;

383

token: JWT;

384

}) => Awaitable<void>;

385

}

386

387

type EventType = keyof EventCallbacks;

388

```

389

390

### Theme Configuration

391

392

```typescript { .api }

393

interface Theme {

394

/** Color scheme for built-in pages */

395

colorScheme?: "auto" | "dark" | "light";

396

/** Logo URL for built-in pages */

397

logo?: string;

398

/** Brand color for built-in pages */

399

brandColor?: string;

400

/** Button text color for built-in pages */

401

buttonText?: string;

402

}

403

```

404

405

### Session Interfaces

406

407

```typescript { .api }

408

interface DefaultSession {

409

user?: {

410

name?: string | null;

411

email?: string | null;

412

image?: string | null;

413

};

414

expires: ISODateString;

415

}

416

417

interface Session extends DefaultSession {}

418

419

type SessionStrategy = "jwt" | "database";

420

```