Skip to content

Commit 6d33052

Browse files
authored
docs(passport): add usage and wrong way inside auth-next-client readme (#2787)
1 parent 9732be9 commit 6d33052

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

packages/auth-next-client/README.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,43 @@ function MyComponent() {
428428
| `isAuthenticated` | `boolean` | Whether user is authenticated |
429429
| `getUser` | `(forceRefresh?: boolean) => Promise<User \| null>` | Get user function for wallet integration |
430430

431+
#### Checking Authentication Status
432+
433+
**Always use `isAuthenticated` to determine if a user is logged in.** Do not use the `session` object or `status` field directly for this purpose.
434+
435+
**Why not `!!session`?**
436+
437+
A `session` object can exist but be **unusable**. For example, the session may be present but the access token is missing, or a token refresh may have failed (indicated by `session.error === "RefreshTokenError"`). Checking `!!session` would incorrectly treat these broken sessions as authenticated.
438+
439+
**Why not `status === 'authenticated'`?**
440+
441+
The `status` field comes directly from NextAuth's `useSession` and only reflects whether NextAuth considers the session valid at the cookie/JWT level. It does **not** account for whether the access token is actually present or whether a token refresh has failed. A session can have `status === 'authenticated'` while `session.error` is set to `"RefreshTokenError"`, meaning the tokens are no longer usable.
442+
443+
**What `isAuthenticated` checks:**
444+
445+
The `isAuthenticated` boolean validates all of the following:
446+
447+
1. NextAuth reports `'authenticated'` status
448+
2. The session object exists
449+
3. A valid access token is present in the session
450+
4. No session-level error exists (e.g., `RefreshTokenError`)
451+
452+
It also handles transient states gracefully — during session refetches (e.g., window focus) or manual refreshes (e.g., after wallet registration via `getUser(true)`), `isAuthenticated` remains `true` if the user was previously authenticated, preventing UI flicker.
453+
454+
```tsx
455+
// ✅ Correct - uses isAuthenticated
456+
const { isAuthenticated } = useImmutableSession();
457+
if (!isAuthenticated) return <div>Please log in</div>;
458+
459+
// ❌ Incorrect - session can exist with expired/invalid tokens
460+
const { session } = useImmutableSession();
461+
if (!session) return <div>Please log in</div>;
462+
463+
// ❌ Incorrect - status doesn't account for token errors
464+
const { status } = useImmutableSession();
465+
if (status !== "authenticated") return <div>Please log in</div>;
466+
```
467+
431468
#### The `getUser` Function
432469

433470
The `getUser` function returns fresh tokens from the session. It accepts an optional `forceRefresh` parameter:

0 commit comments

Comments
 (0)