I want to send a welcome email to the user when logging in to Google using Cloud Functions in Flutter Web, and save the user information to FireStore. I want to create a separate admin and project in the future to manage it directly. Currently, Google login is possible, but Cloud Function deployment is not possible. Below is the Cloud Function code written in JS.
Please let me know what the problem is.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const nodemailer = require('nodemailer');
admin.initializeApp();
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true,
auth: {
user: "[email protected]",
pass: "myPW",
}
});
exports.onUserCreated = functions.auth.user().onCreate(async (user) => {
try {
console.log('User object:', user);
if (!user) {
console.error('User object is undefined');
return;
}
await admin.firestore().collection('auth_users').doc(user.uid).set({
email: user.email || '',
displayName: user.displayName || '',
photoURL: user.photoURL || '',
createdAt: admin.firestore.FieldValue.serverTimestamp(),
lastLoginAt: admin.firestore.FieldValue.serverTimestamp()
});
const mailOptions = {
from: '[email protected]',
to: user.email,
subject: 'welcome!',
text: `Hi, ${user.displayName || ''},`
};
await transporter.sendMail(mailOptions);
console.log('Welcome email sent to:', user.email);
} catch (error) {
console.error('Error in onUserCreated:', error);
}
});
Below is the error message
TypeError: Cannot read properties of undefined (reading 'user')
at Object.<anonymous> (/Users/myproject/Documents/project/test002/functions/index.js:18:40)
at Module._compile (node:internal/modules/cjs/loader:1364:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1422:10)
at Module.load (node:internal/modules/cjs/loader:1203:32)
at Module._load (node:internal/modules/cjs/loader:1019:12)
at Module.require (node:internal/modules/cjs/loader:1231:19)
at require (node:internal/modules/helpers:177:18)
at loadModule (/Users/myproject/Documents/project/test002/functions/node_modules/firebase-functions/lib/runtime/loader.js:40:16)
at loadStack (/Users/myproject/Documents/project/test002/functions/node_modules/firebase-functions/lib/runtime/loader.js:157:23)
at /Users/myproject/Documents/project/test002/functions/node_modules/firebase-functions/lib/bin/firebase-functions.js:56:56
Error: Functions codebase could not be analyzed successfully. It may have a syntax or runtime error
And I would also appreciate it if you could let me know if coding cloud functions in Python would result in fewer errors.