I am having the following application that should authorize with twitter and i am using Firestore. I am using nodejs and the problem i am having is when i am using await
in onRequest that should return a response and the set the values to a firestore database. Below is my code
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const dbRef = admin.firestore().doc("tokens/demo");
const TwitterApi = require("twitter-api-v2").default;
const twitterClient = new TwitterApi({
clientId: "",
clientSecret: "",
});
const callBackUrl = "http://127.0.0.1:5000/lucembot/us-central1/callback";
exports.auth = functions.https.onRequest((request, response) => {
const {url, codeVerifier, state} = twitterClient.generateOAuth2AuthLink(callBackUrl, {
scope: ["tweet.read", "tweet.write", "users.read", "offline.access"],
});
await dbRef.set({codeVerifier, state});
response.redirect(url);
});
exports.callback = functions.https.onRequest((request, response) => {});
exports.tweet = functions.https.onRequest((request, response) => {});
I am getting below error
await dbRef.set({codeVerifier, state});
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1026:15)
at Module._compile (node:internal/modules/cjs/loader:1061:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1151:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
Node.js v17.6.0
2
Answers
Usually await works on functions that return a promise, not on functions that return the request object and expect you to use callbacks or event listeners to know when things are done.
Usually, I would recommend you to use the request-promise module.
But since request-promise has been deprecated, here are other options that don’t depend on the NPM request package. got has been mentioned already, but it depends on 11 other packages.
axios, in contrast, only has 1 dependency (for redirects). Everything else is natively implemented and built on top of the native NodeJS packages.
Here is an example using axios:
or, as a one-liner in JavaScript
The top-level await means that you are trying to use async/await syntax outside the async function. You can run the await statement under the async function.
So, you have to write your:
For more details. check here.