mirror of
https://github.com/SrIzan10/next-auth.git
synced 2026-05-01 10:55:20 +00:00
A living session could be a requirement for specific pages (like dashboards). If it doesn’t exist, the user should be redirected to a page asking them to sign in again.
Sometimes, a user might log out by accident, or by deleting cookies on purpose. If that happens (e.g. on a separate tab), then `useSession({ required: true })` should detect the absence of a session cookie and always return a non-nullable Session object type.
When `required: true` is set, the default behavior will be to redirect the user to the sign-in page. This can be overridden by an `action()` callback:
```js
const session = useSession({
required: true,
action() {
// ....
}
})
if (session.status === "Loading") return "Loading or not authenticated..."
// session.data is always defined here.
```
Co-authored-by: Kristóf Poduszló <kripod@protonmail.com>
Co-authored-by: Lluis Agusti <hi@llu.lu>
BREAKING CHANGE:
The `useSession` hook now returns an object. Here is how to accommodate for this change:
```diff
- const [ session, loading ] = useSession()
+ const { data: session, status } = useSession()
+ const loading = status === "loading"
```
With the new `status` option, you can test states much more clearly.
38 lines
1007 B
TypeScript
38 lines
1007 B
TypeScript
import * as React from "react"
|
|
import { Session } from ".."
|
|
|
|
export interface BroadcastMessage {
|
|
event?: "session"
|
|
data?: {
|
|
trigger?: "signout" | "getSession"
|
|
}
|
|
clientId: string
|
|
timestamp: number
|
|
}
|
|
|
|
export interface NextAuthConfig {
|
|
baseUrl: string
|
|
basePath: string
|
|
baseUrlServer: string
|
|
basePathServer: string
|
|
/** Stores last session response */
|
|
_session?: Session | null
|
|
/** Used for timestamp since last sycned (in seconds) */
|
|
_lastSync: number
|
|
/**
|
|
* Stores the `SessionProvider`'s session update method to be able to
|
|
* trigger session updates from places like `signIn` or `signOut`
|
|
*/
|
|
_getSession: any
|
|
}
|
|
|
|
export type SessionContextValue<R extends boolean = false> = R extends true
|
|
?
|
|
| { data: Session; status: "authenticated" }
|
|
| { data: null; status: "loading" }
|
|
:
|
|
| { data: Session; status: "authenticated" }
|
|
| { data: null; status: "unauthenticated" | "loading" }
|
|
|
|
export type SessionContext = React.Context<SessionContextValue>
|