인프런 커뮤니티 질문&답변

챠챠_님의 프로필 이미지

작성한 질문수

Next + React Query로 SNS 서비스 만들기

react-query SSR 설정하기

next-auth 질문 + 새소식 올려주신거 참고해서 await signIn('credentials', { ...data, redirect: true });수정한후 로그인 후 홈으로 이동안됩니다.

24.05.15 17:23 작성

·

295

·

수정됨

0

안녕하세요 선생님

  1. 새소식 올려주신거 참고해서 await signIn('credentials', { ...data, redirect: true });수정한후 로그인 후 홈으로 이동안됩니다.

home 갔다가 로그인화면으로 이동해버리는데 어디서 이동시키는건지 뒤저봐도 못 찾겠더라구요. 로그인화면으로 새로고침되는듯 합니다...

true만 하고 이전 코드와 다 똑같은데 조언 부탁드립니다 ㅠ

/src/app/(beforeLogin)/_component/Loginmodal.tsx

const onSubmit: SubmitHandler<formProps> = async (data: formProps) => {
		console.log(data);
		try {
			await signIn('credentials', { ...data, redirect: true });
			router.replace('/home');
			console.log('---------------------------------------after LoginModal login')
		} catch(error) {
			console.error(error);
			console.log('아이디와 비밀번호가 일치히자 않습니다.');
		}
	};

 

src/middleware.ts

export async function middleware() {
  const session = await auth();
  console.log(session, '------------------------------middleware session')
  if (!session) {
    return NextResponse.redirect('http://localhost:3001/i/flow/login');
  }
}

// See 'Matching Paths' below to lean more
// 미들웨어를 적용할 라우트로 로그인을 해야하는 페이지
// 페이지 접근관리 하기 쉬워짐
export const config = {
  matcher: ['/compose/tweet', '/home', '/explore', '/messages', '/search']
}

 

/src/auth.ts

import NextAuth, {CredentialsSignin} from "next-auth"
// import CredentialsProvider from "next-auth/providers/credentials"
import Credentials from "next-auth/providers/credentials"
import { NextResponse } from 'next/server';

export const {
  // api 라우트
  handlers: { GET, POST },
  // auth 함수 실행하면 로그인 유무알 수 있다.
  auth,
  // 로그인 하는 함수
  signIn
} = NextAuth({
  pages: {
    signIn: "/i/flow/login",
    newUser: '/i/flow/signup',
  },
  providers: [
    Credentials({
      // You can specify which fields should be submitted, by adding keys to the `credentials` object.
      // e.g. domain, username, password, 2FA token, etc.
      credentials: {
        id: {},
        password: {},
      },
      authorize: async (credentials) => {
        console.log('-------------------------------------------auth.ts');
        const authResponse = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/login`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(credentials)
        })

        // 여기 주목!!! 서버에서 에러가 발생할 때 그 에러 내용이 서버에 담겨 있을 겁니다.
        console.log(authResponse.ok, authResponse.status, authResponse.statusText)
        if (!authResponse.ok) {
          const credentialsSignin = new CredentialsSignin();
          if (authResponse.status === 404) {
            credentialsSignin.code = 'no_user';
          } else if (authResponse.status === 401) {
            credentialsSignin.code = 'wrong_password';
          }
          throw credentialsSignin;
        }
      
        // 로그인 성공
        const user = await authResponse.json();
        console.log('user', user);
 
        // return user object with the their profile data
        return {
          ...user,
          name: user.nickname,
          email: user.id,
        }
      },
    }),
  ]
})

 

 

  1. next-auth 소식이나 말쓰하시는거 들어봐도 아직 안정화가 되지 않은것같은데 선생님은 next-auth를 실무에 도입해도 된다고보시나요? 아니면 nodebird 처럼 express로 하는걸 더 추천하실지 궁금합니다. 넥스트오쓰에서 가입한 사용자를 데이터베이스로 볼수있는지도 궁금하구 어차피 배워야할것이니 이런저런 부족한게 좀 있더라도 밀고나가야하는지.. 여유되실때 확인해주시면 감사하겠습니다.

     

답변 2

1

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

2024. 05. 15. 21:55

signIn에 callbackUrl 옵션이있어 거기에 /home을 넣으세요.

next-auth는 공식문서랑 깃헙보고 스스로 알아낼 수 없는 사람은 쓰면 안 됩니다. 베타라서 버전마다 기능이 너무 많이 바뀌고있기도 하고요. 로그인은 익스프레스 세션같은 백엔드 라이브러리로 구현하는 게 더 쉽지않나싶기도합니다.

챠챠_님의 프로필 이미지
챠챠_
질문자

2024. 05. 15. 22:56

답변감사합니다.

redirect: true로 하고나서 redirectTo 옵션이나 말씀해주신 옵션도 찾아봤는데 제가 찾은곳에서는 보이지 않더라구요ㅠ
https://authjs.dev/reference/sveltekit/actions#signin

그래서 일단은 redirect: false로 두고 차후에 찾아서 수정하려고 합니다.

친절한 답변 감사합니다!

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

2024. 05. 15. 23:13

음 계속 스벨트킷을 보시네요? 스벨트는 리액트랑 다른 프레임워크입니다

챠챠_님의 프로필 이미지
챠챠_
질문자

2024. 05. 16. 09:17

아... 헛질만 하고있었네요

감사합니다.

옵션을 찾아서 어떤게 더 있나 확인해보려고 찾아보다 어휴 감사합니다.

0

인프런 AI 인턴님의 프로필 이미지

2024. 05. 15. 17:26

안녕하세요, 인프런 AI 인턴입니다. 챠챠_님의 질문에 대해 답변드리겠습니다.

질문하신 내용과 비슷한 상황을 겪은 다른 수강생의 질문과 그에 대한 답변이 있어서 이를 참고하시면 도움이 될 것 같습니다. next-auth와 관련하여 로그인 후 홈으로 리다이렉트 되지 않는 문제는 여러 원인으로 발생할 수 있습니다. 해당 문제에 대한 해결 방법을 모색하는 과정에서, 질문하신 내용과 관련된 부분들을 꼼꼼히 검토해보시는 것이 중요합니다.

  1. 로그인 문제: 이 게시글에서는 로그인을 시도했을 때 리다이렉트가 예상대로 작동하지 않는 문제를 다루고 있습니다. 이러한 문제 해결을 위해 next-auth의 버전별 차이 및 signIn 함수 사용 방식에 대한 검토가 필요할 수 있습니다. 로그인 문제 링크에서는 특정 버전의 next-auth에서 발생하는 문제와 그 해결 방법에 대한 논의가 있습니다.

  2. next-auth Login 시 middleware 이슈 질문 드립니다.: 이 게시글은 next-auth를 사용할 때 middleware 관련 이슈를 질문하고 있습니다. 로그인 과정에서 middleware 설정이 올바르게 이루어졌는지 확인하는 것이 중요하며, 로그인 후 리다이렉션 처리에서도 middleware가 영향을 미칠 수 있습니다.

Regarding the stability and adoption of next-auth in production, the decision largely depends on your project requirements and the need for features that next-auth provides. While next-auth offers a convenient way to integrate authentication in Next.js applications, evaluating its compatibility with your project’s architecture and ensuring it meets your security requirements is essential. In some cases, depending on the complexity and specific needs of your application, a custom authentication solution using Express might be more suitable.

next-auth는 계속해서 발전하고 있는 라이브러리이기에 최신 버전의 변경 사항, 알려진 이슈, 그리고 커뮤니티의 해결책을 확인하는 것이 좋습니다. 실무 도입 여부는 해당 프로젝트의 요구 사항과 개발 팀의 next-auth에 대한 이해도 및 지원 능력을 고려하여 결정해야 합니다.

저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다.
현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏
추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.

챠챠_님의 프로필 이미지

작성한 질문수

질문하기