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.
36 lines
833 B
JavaScript
36 lines
833 B
JavaScript
import { useState, useEffect } from "react"
|
|
import { useSession } from "next-auth/react"
|
|
import Layout from "../components/layout"
|
|
|
|
export default function Page() {
|
|
const { status } = useSession({
|
|
required: true,
|
|
})
|
|
const [content, setContent] = useState()
|
|
|
|
// Fetch content from protected route
|
|
useEffect(() => {
|
|
if (status === "loading") return
|
|
const fetchData = async () => {
|
|
const res = await fetch("/api/examples/protected")
|
|
const json = await res.json()
|
|
if (json.content) {
|
|
setContent(json.content)
|
|
}
|
|
}
|
|
fetchData()
|
|
}, [status])
|
|
|
|
if (status === "loading") return <Layout>Loading...</Layout>
|
|
|
|
// If session exists, display content
|
|
return (
|
|
<Layout>
|
|
<h1>Protected Page</h1>
|
|
<p>
|
|
<strong>{content}</strong>
|
|
</p>
|
|
</Layout>
|
|
)
|
|
}
|