I’m trying to execute a login with next.js app router. I started with this:
export default function Login(){
async function LoginExecute(prevState, frmData){
'use server'
try{
const userCredential = await signInWithEmailAndPassword(auth, email, password);
const idToken = await userCredential.user.getIdToken();
await signIn("credentials", {
email: email,
idToken,
redirect: false,
});
}
catch(error){
console.log(error)
throw new Error('Firebase error')
}
}
return <LoginFrm action={LoginExecute} />
}
Nothing seem to work. It kept saying the signIn
method needed to be executed on the client and not the server and I didn’t find anyway to do that. I kept getting error messages that once I’m using action
, that it must be server processed.
So what I did to get it working was a normal API rest call as with page-router or react&node:
export default function Login(){
return <LoginFrm />
}
LoginForm
'use client'
const handlerSubmit=async(e)=>{
e.preventDefault()
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify({ email, password }),
});
const data = await response.json();
const signInResult = await signIn("credentials", {
email,
idToken: data.idToken,
redirect: false,
});
router.push('/'); // Redirect to the homepage or another page after successful login
} catch (error) {
console.error('Login failed:', error);
}
}
return (
<>
<form onSubmit={handlerSubmit} >
My question: is this good code design with app-router principles? i.e. any type of client processing of a form must be done with an API rest call rather than server processing (use server
). E.g. lets say I have to display an error message (which is client), will that also have to be done as API call or could I do it as server processing?