useSession.update를 이용한 사용자 정보 수정하기 | Next Auth

Bori·2024년 1월 21일
0

Next.js

목록 보기
11/12
post-thumbnail

Next Auth를 사용하지 않는 경우, 사용자 정보를 수정할 수 있는 API를 통해 사용자 정보를 변경할 수 있습니다.
하지만 Next Auth를 사용하고 있다면 session의 정보도 업데이트 해야합니다.

Updating the session

useSession hook은 update 메서드를 제공합니다. 이를 통해 session의 정보를 업데이트 할 수 있습니다.

update 메서드에 변경할 값을 인수로 전달하면 session의 정보가 업데이트 됩니다.
다음은 공식 문서의 예제입니다.

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>
        {/*
         * 인수없이 update 메서드를 다음과 같이 사용할 수 있다.
         * 이미 서버를 업데이트 했다고 가정했을 때 session update만 트리거 한다.
         * 아직 인수 없이 update 메서드를 사용하는 것에 대한 필요성을 모르겠다.
         */}
        <button onClick={() => update()}>Edit name</button>
      </>
    )
  }

  return <a href="/api/auth/signin">Sign in</a>
}

다음은 제가 실제 적용한 코드 입니다.

const ProfileEditPage: NextPage = () => {
  const { data: session, update } = useSession();

  const onSubmit: SubmitHandler<EditProfileForm> = async (data) => {
    try {
      const { username, imgUrl } = data;

      // editProfileMutation통해 user 정보를 수정하는 api를 호출한다. 
      editProfileMutation({ username, imgUrl });
      // useSession update 메서드를 이용하여 위의 동일하게 session의 user 정보를 변경한다.
      void update({ username, imgUrl });

      await router.replace('/profile');
    } catch (error) {
      if (isAxiosError<ErrorResponse>(error)) {
        // 에러 처리
        console.log(error);
      }
    }
  };
  
  return (
    <Form onSubmit={handleSubmit(onSubmit)}>
      // 중략...
    </Form>
  );
};

strategy: "jwt"를 사용할 경우, update 메서드는 trigger: "update" 옵션을 통해 jwt callback을 트리거 합니다.
이를 통해 서버의 session 정보를 업데이트 할 수 있습니다.

export const authOptions: NextAuthOptions = {
  session: {
    strategy: 'jwt',
    maxAge: 30 * 24 * 60 * 60, // 30 days
  },
  // ...중략
  callbacks: {
    async jwt({ token, account, user, trigger, session }) {
      // ...중략
      // trigger 옵션이 'update'인 경우
      if (trigger === 'update' && session !== null) {
        const { username, imgUrl } = session as EditProfileRequest; // 이 때 session은 any 타입이므로 해당 객체의 타입을 단언해줌
        // token의 정보를 업데이트
        token.username = username;
        token.imgUrl = imgUrl;
      }

      return await Promise.resolve({ ...token, ...user });
    },
 // ... 중략
};

참고

0개의 댓글