[Next.js / next-auth] TypeError: Failed to construct 'URL': Invalid base URL

나라·2023년 12월 11일
2

Trouble Shooting

목록 보기
3/14

개요

  • 로그인 완료 시 redirect 되지 않고 오류 발생하는 현상
  • app/login 페이지 내에 LoginModal.tsx import (클라이언트 컴포넌트)
  • Next.js(14버전) , next-auth@beta(5버전)

//기존 코드 (app/loginModal.tsx)
   const onSubmit: FormEventHandler<HTMLFormElement> = async (e) => {
    e.preventDefault()
    setMessage('')
    try {
      const response = await signIn('credentials', {
        username: id,
        password,
        redirect: false,
      })
  	route.replace('/')
    } catch (err) {
      console.error(err)
      setMessage('에러발생')
    } 
  } 

클라이언트 컴포넌트라 redirect:false 후 route.push() 로 페이지 전환하려고 했으나 계속되는 오류
(사실 위 코드 외에도 이것저것 시도한 방법이 너무 많음..)
(redirect:true 도 물론 시도해보았지만 계속 실패)

문제 및 해결

signIn이랑 회원가입 로직은 하루종일 붙잡고 있어도 오류때문에 진전이 없는 와중에도
signOut은 처음부터 잘 작동하길래

  const onLogout = () => {
    signOut({ redirect: false }).then(() => {
      axios.post(`${process.env.NEXT_PUBLIC_BASE_URL}/api/logout`, {
        credentials: 'include',
      })
      router.replace('/login')
    })
  }

async,await / then,catch 차이인가 싶어서 수정했더니 제대로 redirect 된다

//수정 코드 (app/loginModal.tsx)
  const onSubmit: FormEventHandler<HTMLFormElement> = (e) => {
    e.preventDefault()
    const callbackUrl = `${process.env.NEXT_PUBLIC_LOCAL}/`
    console.log(callbackUrl)
    signIn('credentials', {
      id,
      password,
      redirect: true,
      callbackUrl,
    })
      .then((response) => {
        console.log(`response:${response}`)
      })
      .catch((error) => {
        console.log(`error:${error}`)
      })
  }

//auth.ts
import NextAuth from 'next-auth'
import CredentialsProvider from 'next-auth/providers/credentials'
import axios from 'axios'
export const {
  handlers: { GET, POST },
  auth,
  signIn,
} = NextAuth({
  pages: {
    signIn: '/login',
    newUser: '/createAccount',
  },
  providers: [
    CredentialsProvider({
      async authorize(credentials: Record<any, any>, req: any) {
        console.log(credentials)
        const authResponse = await axios.post(
          `${process.env.NEXT_PUBLIC_AUTH_URL}/api/login`,
          {
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              id: credentials.id,
              password: credentials?.password,
            }),
          },
        )
        const user = await authResponse.data
        console.log('User from server:', user)
        return {
          email: user.id,
          name: user.nickname,
          image: user.image,
          ...user,
        }
      },
    }),
  ],
  callbacks: {
    jwt({ token }) {
      console.log('auth.ts jwt', token)
      token.userId = token.test = 'test'
      return token
    },
    session({ session, newSession, user }) {
      console.log('auth.ts session', session, newSession, user)
      return session
    },
  },
  events: {
    signOut(data) {
      console.log(
        'auth.ts events signout',
        'session' in data && data.session,
        'token' in data && data.token,
      )
      if ('session' in data) {
        data.session = null
      }
      if ('token' in data) {
        data.token = null
      }
    },
    session(data) {
      console.log(
        'auth.ts events session',
        'session' in data && data.session,
        'token' in data && data.token,
      )
    },
  },
})

^^.......ㅠ

profile
FE Dev🔥🚀

1개의 댓글

comment-user-thumbnail
2024년 1월 7일

https://github.com/nextauthjs/next-auth/issues/9279

여전이 남아있는 버그입니다 ㅜㅜ

답글 달기