Multiple errors when importing nodemailer in nextjs API - next.js

I am trying to have an API endpoint pages/api/sendEmail that uses nodemailer to send an email, but for some reason I get the error Can't resolve 'fs' when I try to use nodemailer with let nodemailer = require('nodemailer'). I have seen multiple posts about this always saying that this is due to the fact that I am trying to execute this in the frontend, but I am doing it in the API. I have also seen posts like this one and tried the fixes by modifying next.config.js, but after all the fixes this new error appeared:
Uncaught TypeError: util__WEBPACK_IMPORTED_MODULE_3__.TextEncoder is not a constructor
What I don't understand here is why can't I use the package in the API, since it is executed on the backend. I have seen multiple tutorials like this one that do the exact same thing.

Related

NextJS and deploying app - What's the use of the /api folder when wanting to make API calls in production (deployed)?

I just went through the steps of creating a CRUD app with NextJS. Everything works fine when I run the app on my development environment npm run dev.
Then I tried to deploy it to Vercel.
The build fails, and the error that comes up is:
AxiosError: connect ECONNREFUSED 127.0.0.1:3000
...
Build error occurred
Error: Failed to collect page data for /beers/[id]
at /vercel/path0/node_modules/next/dist/build/utils.js:963:15
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
type: 'Error'
I get it: when I make my API requests, the app is using HTTP:localhost:3000, so if deployed, it won't reach.
Then comes my question: locally, I run requests as such, for example:
import axios from 'axios';
axios.defaults.baseURL = "http://localhost:3000";
export const getAllBeers = () => axios.get<BeerData[]>('/api/beers');
and everything works.
I tried to troubleshoot my error. I figured I needed to adjust my baseUrl to the deployment server's address. But it still wouldn't work. And then in the few posts I read, and even in the docs, it says:
Write server-side code directly
As getStaticProps runs only on the server-side, it will never run on
the client-side. It won’t even be included in the JS bundle for the
browser, so you can write direct database queries without them being
sent to browsers.
This means that instead of fetching an API route from getStaticProps
(that itself fetches data from an external source), you can write the
server-side code directly in getStaticProps.
doc source
So after following their tutorial, I'm now confused on the purpose of this /api folder, and in which specific case it's useful? When we want to use the getStaticProps for example.
If anybody could explain with an example? That'd be fantastic. Thank you!

Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2

I have a NodeJS Firebase Function that uses firebase-admin sdk. It has been working alright since last year. In the last 2 weeks, the following error started showing in the log:
Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: 404 page not found
Could it be an issue with the version of "firebase-admin": "^7.3.0" I am using?
Have anyone faced the same issue and can you offer some direction on what might have been the cause?
This looks like a problem with NodeJS, the version 8 is no longer supported as per the documentation. Deployment of functions to the Node.js 8 runtime was disabled in the Firebase CLI on December 15, 2020 and that is most likely why you are facing the 404 error.
To migrate to a newer supported version of the NodeJS runtime, use the documentation.
Also, I do not suspect any issue with your firebase-admin version 7.3.0.
I have the same error, but I was already on Node 12. Also, the function was running well for years and now is crashing due to this :/
The only solution that worked for me was to change auth to admin from default to explicit passing of service-account.json like is described here in docs https://firebase.google.com/docs/reference/admin/node/admin.credential#cert
For those who are deploying to Google Cloud Functions, requirements:
Node >= 10
Initialisation:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();

DialogFlow "Webhook call failed. Error: UNKNOWN."

I have a DialogFlow setup using a firebase function for fulfillments.
I attempted to add two regions to .region() in my index.js file. This led to me deleting my existing firebase function (which had been running on "us-central-1") and adding two new ones for the newly added regions.
After doing so, my dialogflow setup completely fails to do fulfillments. Instead, i get "Webhook call failed. Error: UNKNOWN" with no other details. I tried removing .region() in my index.js, thereby creating a new firebase function similar to the original, but without luck.
I have also tried to add my fulfillment code directly in the inline editor, but this does not work either.
I am at a loss for what to do here. Has anyone experienced similar issues or perhaps know a fix? Please note that the setup worked completely fine prior to adding .region() and deleting the existing firebase function.
NOTE: I am getting a weird error when deploying through the inline editor: "Permission 'cloudfunctions.functions.SetIamPolicy' denied on resource '(my resource)' (or resource may not exist)."
Regarding the following error:
Permission 'cloudfunctions.functions.SetIamPolicy' denied on resource '(my resource)' (or resource may not exist).
I also encountered this when I deleted the function and tried to redeploy it.
I discovered that this occurs when the user (i.e. you) deploying the function does not have sufficient permissions to set IAM policies. In my case, the project was owned by another user whilst I had limited access. After being given owner access, although you likely only need permissions to manage IAM, the function deploys without any errors.
Although you moved the location of the function, you don't mention that you changed the URL for the webhook in Dialogflow to reflect this new location. The URL for Firebase Cloud Functions include the region where the function runs, so if you change the region, you also need to change the fulfillment URL.

FIREBASE WARNING: Invalid query string segment - Warning when deploying simple Firebase Cloud function

This morning I started noticing a large amount of "FIREBASE WARNING: Invalid query string segment" errors in my functions log. In an attempt to figure out what was going on I ended up making various changes to function and deploying all my cloud functions several times.
While doing this I noticed that I was getting the error on a function that:
Does not have a Firebase Query in it.
Has not been invoked in months (it's a test function).
This leads me to believe that a change was made Firebase Cloud Functions recently that may be sporadically generating this error on deploy and/or execution of cloud functions regardless of whether the function has anything to do with real time database queries. Has anybody else noticed this error or have any insight into why it is occurring?
Relevant part of my cloud index.js file is as follows (should be enough to replicate the issue):
const cors = require('cors')({origin: true});
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const firebaseRef = admin.database().ref();
const firestoreRef = admin.firestore();
exports.testCloudFunctions = functions.https.onRequest((request, response) => {
cors(request, response, () => {
const params = request.query;
console.log(params)
response.status(200).send({success: true, message: "Test Successful", params: params});
});
});
After talking with Firebase support, I learned this bug was introduced in the npm dependency #firebase/database: 0.1.10. You will have this dependency if you also have the latest firebase-admin dependency.
The warning
shouldn't have any impact on the function's overall processing.
If you want to remove the warning, you can force the npm dependency of #firebase/database: 0.1.9. I tested this adjustment and the warning was removed from my Firebase Console Logs.
The support agent also stated the fix has been made, but not released, so I would expect #firebase/database: 0.1.11+ to not experience this bug.
Looks like a recently introduced bug which will hopefully be fixed soon.
We having the same problem today. Maybe some maintenance in the platform. Maybe some Google dev will soon say something about this.
It seems they are having issues with notification.
You can check for the status here: https://status.firebase.google.com/
I am new to Firebase today.
The code snippet I generated for the Firebase db connection had this firebase.js :
<script src="https://www.gstatic.com/firebasejs/4.10.0/firebase.js"></script>
This is generating the message : 'FIREBASE WARNING: Invalid query string segment:', but is also returning the data.
If I use a different version of firebase.js, either .../4.8.0/... or .../4.9.0/... , no error/warning message is generated.
I am running Google Chrome on Windows 10.
Update: It's officially a bug and you can ignore it until they release a fix in the next update or add version of #firebase/database: 0.1.9 to dependencies if you don't want to wait.
Seems like an internal error or change. Also getting this firebase warning and my code was working fine yesterday using '' syntax as well. However my function still works. Looks like they're doing some heavy dev work on it as its in beta and issues are coming up now and then.
Wait for fix or report here:
https://firebase.google.com/support/contact/bugs-features/
Status here (fixes usually take time to appear on here):
https://status.firebase.google.com/
Copy of 48830081 and possibly 48832566

Cloud Functions for Firebase sometimes have Invalid credential error

Not appear every time, but sometimes this error appears in the log:
FIREBASE WARNING: {"code":"app/invalid-credential","message":"Credential implementation provided to initializeApp() via the \"credential\" property failed to fetch a valid Google OAuth2 access token with the following error: \"read ECONNRESET\"."}
Is there any way to handle this kind of error like retry?
Or is it okay to ignore it?
Just ensure that your machine time auto sync. and not manualy,
And your XXX......json from firebase is the latest downloaded. (if you dont sure, download it again - and this file will be the newer one)
that what helped me.
I am also facing this issue. Looks like it retries and get the job done but cloud functions are taking time to process data.

Resources