인프런 커뮤니티 질문&답변
로그인 클릭시, Failed to construct URL: Invalid base URL 에러로 인해서 리다이렉트가 되지 않습니다
해결된 질문
작성
·
2.3K
·
수정됨
5
‘next-auth로 로그인하기’ 강의를 다 듣고 나서
로그인 버튼을 클릭했더니 아래의 에러가 발생하고
'/home'으로 리다이렉트가 되지 않습니다.
TypeError: Failed to construct 'URL': Invalid base URL
at signIn (react.js:172:19)
at async onSubmit (VM5774 LoginModal.tsx:29:13)
에러 로그를 보고 처음에는 URL 설정이 문제인가 싶었는데
URL은 문제가 없었습니다
#.env
AUTH_URL=http://localhost:9090 
AUTH_SECRET=mustkeepinsecret
// auth.ts
CredentialsProvider({
      async authorize(credentials) {
        console.log(credentials);
        const authResponse = await fetch(`${process.env.AUTH_URL}/api/login`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            // credentials
            id: credentials.username,
            password: credentials.password,
          }),
        });
        console.log(authResponse);
        // 로그인 실패
        if (!authResponse.ok) {
          return null;
        }
        // 로그인 성공
        const user = await authResponse.json();
        return user;
      },
    }),
// src\\mocks\\handlers.ts
http.post('/api/login', () => {
    console.log('로그인');
    return HttpResponse.json(
      {
        userId: 1,
        nickname: '제로초',
        id: 'zerocho',
        image: '/5Udwvqim.jpg',
      },
      {
        headers: {
          'Set-Cookie': 'connect.sid=msw-cookie;HttpOnly;Path=/',
        },
      },
    );
  }),
실제로 로그인 버튼을 클릭하면 터미널에 handlers.ts 에 작성한 console.log('로그인'); 가 제대로 출력이 되고
CredentialsProvide의 authorize에 작성한 console.log(credentials); 역시 제대로 출력이 됩니다
에러 메세지를 보면 signIn 관련 문제인 것 같은데 이 역시 강사님이 작성해주신 내용 그대로 작성했는데 뭐가 문제인지 모르겠네요ㅠ
const onSubmit: FormEventHandler<HTMLFormElement> = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    setMessage('');
    try {
      await signIn('credentials', {
        username: id,
        password,
        redirect: false,
      });
      // 로그인 성공하면 리다이렉션
      router.replace('/home');
    } catch (e) {
      console.error(e);
      setMessage('아이디와 비밀번호가 일치하지 않습니다');
    }
  };
답변 4
1
제로초(조현영)
지식공유자
https://github.com/nextauthjs/next-auth/issues/9279
이 이슈인 것 같은데 이게 해결되야할 것 같습니다.
beta3 버전 설치하시거나 beta5 나오면 그걸로 올려보세요.
1
0
0
kraf
질문자
안녕하세요!
서버 컴포넌트에서 사용하는 redirect뿐만 아니라
import { redirect } from 'next/navigation';
  // redirect는 반드시 try, catch 밖에다
  if (shoudlRedirect) redirect('/home');
클라이언트 컴포넌트에서 useRouter()로 사용하는 리다이렉트도 모두 다 try catch 밖에 사용하면 건가요?
강의내용에서 전자는 강사님이 언급해주셨는데
후자의 경우 강사님도 try문 안에 사용하셔서 질문드립니다!
그리고 try catch 외부로 redirect를 사용해도 에러는 계속 발생합니다ㅠ






console.log(authResponse) 의 결과는 위와 같습니다.


오 그렇네요... next auth 이슈를 직접 찾아보는 방법이 있었군요! 감사합니다