Photo by Bench Accounting on Unsplash
Next.js Session exist or not (For show login or logout button according to session )
For show login or logout button according to session Server side rendering
import { useSession, getSession } from "next-auth/react"
export default function Page() {
const { data: session } = useSession()
if (typeof window !== "undefined") return null
if (session) {
return (
<>
<h1>Protected Page</h1>
<p>You can view this page because you are signed in.</p>
</>
)
}
return <p>Access Denied</p>
}
export async function getServerSideProps(context) {
return {
props: {
session: await getSession(context),
},
}
}
check session exist
{session?.user && (
<h4>session exist </h4>
)}
check if session not exist
{!session && (
<h3>no session</h3>
)}