//기존 코드 (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,
)
},
},
})
^^.......ㅠ
https://github.com/nextauthjs/next-auth/issues/9279
여전이 남아있는 버그입니다 ㅜㅜ