I'm creating a website with nextjs 13 (app router) and incorporating firebase. I've come across suggestions to combine next-auth and firebase auth for using firebase auth effectively. Accordingly, I have configured my firebase
Here is the firebase configuration:
import { initializeApp, getApps } from "firebase/app";
import { getAuth } from "firebase/auth";
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};
// Initialize Firebase
const firebase_app = getApps().length === 0 ? initializeApp(firebaseConfig) : getApps()[0];
const auth = getAuth(firebase_app);
export { firebase_app, auth }
The issue I'm facing is that although I can sign in successfully, when attempting to utilize auth from firebase, it returns null/undefined.
Below is the code snippet for updating the password:
import { NextResponse } from 'next/server'
import { EmailAuthProvider, updatePassword, reauthenticateWithCredential } from "firebase/auth";
import { auth} from '@/firebase/config'
export async function POST(request: Request) {
const res = await request.formData()
const old_password = res.get('old-password')?.toString()
const new_password = res.get('new-password')?.toString()
const confirm_password = res.get('confirm-password')?.toString()
const user = auth.currentUser;
console.log("user: ", user)
if(!old_password || !new_password || !confirm_password) {
return NextResponse.json({ status: 400, statusText: "Missing info" })
}
else if(new_password !== confirm_password) {
return NextResponse.json({ status: 400, statusText: "Passwords do not match" })
}
if(user != null){
const userEmail = user.email || "";
const credential = EmailAuthProvider.credential(userEmail, old_password);
reauthenticateWithCredential(user, credential).then(() => {
// User re-authenticated.
updatePassword(user, new_password).then(() => {
// Update successful.
return NextResponse.json({ status: 200, statusText: "Password updated" })
}).catch((error) => {
// An error ocurred
return NextResponse.json({ status: 500, statusText: "Error updating password" })
});
}).catch((error) => {
// An error ocurred
if(error.code === "auth/wrong-password"){
throw new Error("wrong-password");
}
else{
throw new Error("error-reauthenticating");
}
//return NextResponse.json({ status: 401, statusText: "Incorrect password" })
});
}
else{
// If not logged in, redirect to login page
return NextResponse.json({ status: 401, statusText: "Not logged in" })
}
}
Would it be advisable to discontinue using next-auth? Alternatively, are there other potential solutions?