I am building an app in NextJS which uses Firebase authentication. After successful authentication, I then wish to fetch additional details about the customer stored within a mongodb instance (or create a new document for the customer on first login). Because I cannot access the firebase auth object inside getServerSideProps, I have to wrap the dashboard in another component which initiates the firebase auth, then redirects to dashboard passing the user.uid as a parameter to fetch customized/dynamic content inside getServerSideProps. I have created a dashboard.js, and then a dashboard/[id].js.
dashboard.js
export default function DashboardAuth(props) {
const [user, loading, error] = useAuthState(firebase.auth())
if (user){
return window.location.href = `/dashboard/${user.uid}`
}else{
return <SignIn/>
}
}
/dashboard/[id].js
export async function getServerSideProps({ params }) {
let userData
console.log("Logging in ")
const { db } = await connectToDatabase();
console.log("connected to database, awaiting query response with uid")
const findUserResp = await db
.collection("users")
.findOne({'uid': params.id})
if(findUserResp ){
console.log("user data exists")
userData = {
uid: findUserResp.uid,
email: findUserResp.email,
displayName: findUserResp.displayName,
photoURL: findUserResp.photoURL,
storageQuoteRemaining: findUserResp.storageQuoteRemaining,
emailVerified: findUserResp.emailVerified,
currentPage: '/dashboard'
}
}else{
console.log("user data does not exist")
userData = {
uid:params.id,
email: '',
displayName: '',
photoURL: '',
storageQuoteRemaining: 0,
emailVerified: false,
currentPage: '/dashboard'
}
const addUserResp = await db
.collection("users")
.insertOne(userData)
}
console.log("returning userdata below")
console.log(userData)
return {
props: {
userData
}
}
}
export default function Dashboard(props) {
const [user, loading, error] = useAuthState(firebase.auth())
const userContext = getUserContext()
useEffect(() => {
userContext.handleCurrentUser(props.userData)
}, []);
if (user && props.userData.uid === user.uid){
return <Layout children={<CreateItem/>}/>
}else{
return <SignIn/>
}
}
My main issue is that after the user is initially added to mongodb on first login, immediatley after redirect to [id].js, I am presented with an error
Error: Error serializing `.userData._id` returned from `getServerSideProps` in "/dashboard/[id]".
Reason: `object` ("[object Object]") cannot be serialized as JSON. Please only return JSON serializable data types.
but on refresh this disappears.
Also I don’t like how I have written my redirect but useRouter does not work. Any advice on how to better do this would be appreciated.