728x90
useSession()
- 페이지 로딩없이 session을 업데이트 할 수 0
- 만일 인수를 보내지 않으면 서버로부터 리로드 된다.
- 만일 session에서 데이터를 변경하고 싶은 경우
// pages/profile.tsx
import { useSession } from "next-auth/react"
export default function Page() {
const { data: session, status, update } = useSession()
if (status === "authenticated") {
return (
<>
<p>Signed in as {session.user.name}</p>
{/* update함수를 사용해서 백엔드에 보냄 */}
<button onClick={() => update({ name: "John Doe" })}>Edit name</button>
{/* session을 가져오는 코드가 다시 업데이트 된다고 생각하면됨*/}
<button onClick={() => update()}>Edit name</button>
</>
)
}
return <a href="/api/auth/signin">Sign in</a>
}
// auth.ts
export default NextAuth({
...
callbacks: {
// Using the `...rest` parameter to be able to narrow down the type based on `trigger`
jwt({ token, trigger, session }) {
if (trigger === "update" && session?.name) {
// Note, that `session` can be any arbitrary object, remember to validate it!
token.name = session.name
}
return token
}
}
})
getSession()
- 사용가능하긴 하지만 서버 사이드에서만 getServerSession() 사용하길 권장한다.
-> v.5 auth()로 변경
- 리엑트 컨텍스트 밖에서 session을 불러와야할 때 사용한다.
- 프로미스를 반환한다.
async function myFunction() {
const session = await getSession();
const session2 = await auth();
/* ... */
}
결론 (Next.js + Auth.js(Next-Auth)
1. Client Side일 경우,
'use client'
+ useSession()
사용
2. Server Side일 경우,
'use server'
+ auth()
사용
** 여기서 auth는 Provider를 사용해 만들어놓은 src/auth.ts(로그인 로직이 담겨있음)에서 가져온다.
[참고] https://next-auth.js.org/tutorials/securing-pages-and-api-routes
Securing pages and API routes | NextAuth.js
You can easily protect client and server side rendered pages and API routes with NextAuth.js.
next-auth.js.org
728x90
반응형
'라이브러리' 카테고리의 다른 글
Avatar 컴포넌트 안에서 이미지 비율 안깨지게 하기 with Shadcn/ui (0) | 2024.07.08 |
---|---|
React-query를 이용한 무한 스크롤 구현 with react-intersection-observer (1) | 2024.03.05 |
요즘 Redux 대신 React-Query(tanstack-query)가 대세인 이유 (0) | 2024.03.04 |
티스토리 hELLO 스킨 + overstackflow-dark highlight 스킨 적용기 | 라이트 모드일 때 바뀌는 폰트 컬러 수정 (0) | 2024.02.27 |