[Next] 유저정보 수정 후 바로 서버 세션 업데이트하기 (update server session)

    728x90
    반응형

     

     

    [Next] 유저정보 수정 후 바로 서버 세션 업데이트하기 (update server session)

    요즘 포폴용으로 sns + 소개팅 사이트를 만들고 있습니다.

    여기엔 회원가입을 한 후에 유저 정보를 등록하는 프로세스가 있습니다.

    회원가입 했을때 서버 세션엔 정보가 텅빈 상태에서 유저정보를 입력완료하면 서버세션도 업데이트가되어야

    그 다음 페이지로 이동했을때 정보들이 제대로 나오게 됩니다.

    useSession을 이요하면 더 편할 수도 있지만, 이는 클라이언트 컴포넌트에만 사용할 수 있는 함수라서 서버 사이드 랜더링으로 가져온 데이터들에는 적용되지 않아서.. 어쩔수없이 서버 컴포넌트에서 서버 세션을 업데이트할 수 있는 방법을 찾아야 했습니다.

    물론 클라이언트 쪽으로 다 변경하면 되긴했지만,, 서버쪽으로 해보고 싶어서,,

    위 관련해서 삽질하다가 작업 완료 했고 이 내용을 차후에 저도 기억하고 싶어서 블로그에 남깁니다.

    물론 지금보다 더 세련되고 멋지게 리팩토링, 더 좋은 방법이 있겠지만

    이것 때문에 몇일 삽질한 저에겐.. 지금이게 최선이라 ㅎㅎ

    더 좋은 방법이 있다면 댓글 부탁드립니다.

     

     

     

    클라리언트 코드

     

    /usersetting.tsx

    ...
    const response = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/user/setting`, {
      method: 'PATCH',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(userSettingObj),
    });
    
    if (response.ok) {
      const sessionUpdateInfo = await response.json();
      await updateSession(sessionUpdateInfo);
      router.push('/');
    }
    ...

     

    변경된 유저 정보를 userSettingObj 객체에 넣어서, 유저정보를 데이터베이스에서 업데이트 해줍니다.

    그리고 성공하게 되면 서버 세션을 업데이트해줄 함수 호출

     

    ../_lib/updateSession.ts

    import { getCsrfToken } from 'next-auth/react';
    
    export const updateSession = async (updatedUser: any) => {
      try {
        const csrfToken = await getCsrfToken();
        if (!csrfToken) {
          throw new Error('Failed to get CSRF token');
        }
        
        const response = await fetch('/api/session/update', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'X-CSRF-Token': csrfToken,
          },
          body: JSON.stringify({ user: updatedUser }),
        });
    
        if (!response.ok) {
          throw new Error('Failed to update session');
        }
    
        const session = await response.json();
        console.log('Session updated', session);
      } catch (error) {
        console.error('Error updating session', error);
      }
    };

    이 함수에선 수정한 유저정보를 가져와서

    넥스트 서버 api를 호출함

     

     

     

     

     

    서버 코드

    클라이언트 함수에서 받은 유저 정보를

    unstable_update로 호출해준다.

    그러면 서버 세션 업데이트 성공!

    /api/session/update/route.ts

    import { NextResponse } from 'next/server';
    import { unstable_update } from '@/auth';
    
    export async function POST(req: any) {
      try {
        const body = await req.json();
        const response = await unstable_update({ user: body.user });
        if (!response) {
          return NextResponse.json({ error: 'Failed to update user in database' }, { status: 500 });
        }
    
        return NextResponse.json(response.user, { status: 200 });
    
      } catch (error) {
        console.error('Error updating session:', error);
        return NextResponse.json({ error: 'Failed to update session' }, { status: 500 });
      }
    }

     

     

     

     

     

     

     

     

     

     

    참고!

    https://www.heropy.dev/p/MI1Khc

     

    Auth.js(NextAuth.js) 핵심 정리

    Auth.js(NextAuth.js)는 Next.js 프로젝트의 사용자 인증 및 세션 관리를 위한 라이브러리로 Google, GitHub 등의 다양한 인증 공급자를 지원하며, Next.js의 서버와 클라이언트 측 모두에서 인증 및 세션 관리

    www.heropy.dev

     

     

    728x90
    반응형

    댓글