Hi i'm new to next js and had a few questions regarding using firebase authentication client side and server side. I have both firebase admin and firebase client sdks setup in my project. I have a signup page user routes to. They fill in name email and password. I'm using client side to authenticate with email and password createUserWithEmailAndPassword when the user submits the form on the signup page.
Questions: [1]
I want to save the auth response of user name and uid to firestore db when user is created. Should I do this in the same submit handler as the auth response happens ?
const onSignup = async ({ email, password }: Tfields) => {
try {
const response = await auth.signup(email, password);
/ *** DO I save to firestore DB here ? **/
// route to authenticated page
router.push("/account");
} catch (error) {
});
}
};
[2] If calling firestore from handler above should I be calling firestore directly using the firebase client side sdk or should I create an api route in nextjs called createDBUser and call the api from handler. Wouldn't this be safer connecting to firestore using api instead of directly with client side sdk ?
[3] Example authorized route like /account this is essentially a SSG at build time. Wont this show nothing on the page at first which is not very SEO friendly. Only the header SEO component will be viewable at first until the firebase client side check happens ?
const Account = () => {
const [user, setUser] = useState<any>(null);
const handleUser = (user) => {
setuser(user)
}
useEffect(() => {
const unsubscribe = onIdTokenChanged(getAuth(), handleUser);
return () => unsubscribe();
}, []);
return (
<div>
<Head>
<title>Authorized User page</title>
<meta
name="description"
content="this is john doe's page with all his account pages"
/>
</Head>
{user && <div>
<div>This is a authenticated account page</div>
</div> }
</div>
);
};
export default Account;
Or Should I be using getServerSideProps in the account page instead to check if user is logged in instead of doing this in the useEffect. Wouldn't this have all the content rendered on the server before its served to the user ? Also I would be able to inject users name inside the seo header as it will be rendered on server before hand.
CodePudding user response:
Interacting with Firestore directly or via a server depends on your case and opinions may vary. But is it worth adding another API route, verifying user tokens and then adding data to Firestore when that can be directly and secured using security rules? Yes, you can add data to Firestore right after createUserWithEmailAndPassword()
creates a user.
Routing Firestore requests via your API would be useful if you need any sort of rate limit on updating documents or any operations.
For server side rendered web apps, I would recommend using sessions cookies so you can authenticate user before render. Here you would have to verify the cookie using Admin SDK and and fetch data to show before page renders.