Firebase 'internal' error when using Functions and Admin - javascript

I am having trouble with some functions that have been working previously. I have created a function to let the user create another user and it was working fine. Functions that do not use Admin works fine just as before.
However, due to some Firebase updates, the function broke and I am getting an 'internal' error. I had to change import firebase from "firebase/app"; to import firebase from "firebase/compat/app"; as well as import "firebase/compat/functions"; but that did not work, as well as updating firebase to "^9.8.1", but that did not work either.
Here is my web function:
async registerUser(userInfo) {
const functions = getFunctions();
const createUser = httpsCallable(functions, "createUser");
// Used to have this:
// let createUser = firebase.functions().httpsCallable("createUser");
//Call to function where it breaks.
return await createUser({
//User data here
})
.then(
//stuff happens here
).catch((error) => {
//Error happens here
})
}
Here is the function that was already deployed in Firebase:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.createUser = functions.https.onCall(async (userData) => {
return await admin
.auth()
.createUser(userData)
.then(() => {
return { isError: false };
})
.catch((error) => {
return { isError: true, errorMessage: error };
});
});
Here is the response log:
Request Method: OPTIONS
Status Code: 403
Referrer Policy: strict-origin-when-cross-origin
alt-svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"
content-length: 305
content-type: text/html; charset=UTF-8
date: Tue, 24 May 2022 16:04:14 GMT
server: Google Frontend

You can refer to the Admin SDK error handling page and check the Structure of the error, the refer to policy: strict-origin-when-cross-origin part gives us a good starting point.
But first, we can see the root cause of this issue as in the same page we have a table for Platform error codes where:
INTERNAL | Internal server error. Typically a server bug.
In the Firebase Admin Authentication API Errors we have a similar table where:
auth/internal-error | The Authentication server encountered an unexpected error while trying to process the request. The error message should contain the response from the Authentication server containing additional information. If the error persists, please report the problem to our Bug Report support channel.
Now talking about the cors message, this question suggests:
Consider importing like this, as shown in the samples:
const cors = require('cors')({origin: true});
And the general form of your function will be like this:
exports.fn = functions.https.onRequest((req, res) => {
cors(req, res, () => {
// your function body here - use the provided req and res from cors
})
});
You might need to make some changes to the structure as the question has some time, so I will also leave the reference to the Call functions via HTTP requests and check if it works for you.
I will follow up if you provide updates and consider submitting a bug report as previously mentioned by the documentation if this is necessary.

Related

Axios doesn't create a cookie even though set-cookie header is there?

Front-End: [Axios]
const formSubmit = async (e) => {
e.preventDefault()
const formData = new FormData(e.target)
const email = formData.get('email')
const password = formData.get('password')
try {
const res = await axios.post('http://172.16.2.19:3001/api/v1/auth/login', {
email,
password,
})
console.log(res.data) // its okay, I can login if email & password are correct.
} catch (error) {
console.log(error)
}
}
Back-End [Nodejs ExpressJs]:
Inside App.js:
const cors = require('cors')
app.use(cors({ credentials: true }))
Inside Login.js (/auth/login endpoint):
// ... code, then... if email & password are correct:
// 3600000ms = 1hour
res.cookie('jwt', token, { httpOnly: true, expires: new Date(Date.now() + 3600000 })
res.status(200).json({
status: 'success'
token,
data: userDoc,
})
Then, when I login in my browser:
I can login successfully, but no cookies will be created, see:
The front-end http service (react app) is running on http://172.16.2.19:3000
The back-end http service (expressjs) is running on http://172.16.2.19:3001
The axios requests I'm sending from the front-end are requesting: http://172.16.2.19:3001
So what's the problem?
The problem that no cookies are getting created in the browser is preventing me from continuing to design the front-end application, because if I wanted to request anything from my API, I have to be authenticated, all the routes on the API I made are protected, so if I wanted to request anything from the API, I will have to send my jwt token along with the request.
edit **:
here's the response from the /auth/login endpoint after successfully logging in:
I am using brave browser, the latest version.
I tried this on firefox, it has the same behavior.
GUYS GUYS GUYS I found it!!!! after 3 hours of researching, let me save your time:
For anyone having the same problem, all you have to do is
change your backend code from:
const cors = require('cors')
app.use(cors({ credentials: true }))
to
app.use(cors({ credentials: true, origin: true }))
and make sure you're using withCredentials: true on the front-end with every request (the login POST method and all the other requests that requires authentication)
why?
setting origin property to true is going to reflect the request origin, the origin property can be a string if you wanted to specify a particular domain, ex: http://localhost:3000. But if you have more than one client, setting this to true is a wise choise.
and for those of you wondering about mobile devices in case of specifying a string for the origin field with one particular domain. This problem of cors only happens in browsers, any other client doesn't use that CORS policy.
I would check by passing {withCredentials: true} as the third argument to the axios method to allow the browser to set the cookie via the request.
I don't think it is correct to use the backend to save cookies, as cookies is a browser feature separate from the database. I might be wrong though. When the post is successful, res will return a token. You save this token in the browser's local storage.
const formSubmit = async (e) => {
e.preventDefault()
const formData = new FormData(e.target)
const email = formData.get('email')
const password = formData.get('password')
try {
const res = await axios.post('http://172.16.2.19:3001/api/v1/auth/login', {
email,
password,
})
//browsers local storage
localStorage.setItem('access_token',res.data.access);
localStorage.setItem('refresh_token',res.data.refresh);
console.log(res.data) // its okay, I can login if email & password are correct.
}
You will then have to create an authorization header as such
headers:{
Authorization: localStorage.getItem('access_token')
? 'JWT '+localStorage.getItem('access_token')
: null
}

ERR_CERT_AUTHORITY_INVALID with axios in browser

I set a API https server with self-signed cert.
And I am setting a axios https-api call in a function that will run on client's side only. Then when it called the api, it threw an ERR_CERT_AUTHORITY_INVALID
I noticed many articles have motioned below code on how to by pass this.
// At instance level
const instance = axios.create({
httpsAgent: new https.Agent({
rejectUnauthorized: false
})
});
instance.get('https://something.com/foo');
// At request level
const agent = new https.Agent({
rejectUnauthorized: false
});
axios.get('https://something.com/foo', { httpsAgent: agent });
But this popular code only works on server side. And then I noticed that this error is triggered by chrome. So chrome should be the root cause, although I was writing javascript
So, I noticed people have talked about to configure either below one of these. I tried all and doesnt work at all
1.Insecure content
=> this is about http only. So this is not a solution for http
enable the domain when the site pop up.
=> This is the tricky part. Since I host my code on vercel. So at first, it is identified as secure. The error only prompt when I click submit button in my website in which it calls my API server which is in other domain, with a self-signed cert only.
For example:
const handleSubmit = async (e) => {
e.preventDefault();
const newPost = {
theme: theme,
content: content,
};
try {
const res = await axios.post(
`${process.env.NEXT_PUBLIC_API_URL}/${username}`,
newPost
);
} catch (err) {
console.log(err);
}
Is there a easy way to let the chrome be able to call the api?

GraphQL not making request to WP API

Thanks in advance!
I'm pulling data from a WP Rest API and when spin up the wordpress site on my local machine with the address http://localhost:8000 and got to the graphqli playground on http://localhost:3000/api/graphql and i enter a query i get the expected results and i can consume the data happily in react but once i change the WP rest API address to http://example.com/cms i get back an error. The only thing that changes is the URL so i'm guessing it has to do with CORS.
Inspecting the browser window there is no CORS errors so i can rule out CORS being an issue. The strange thing is that when i make the api call via postman i get the response i expect, when i type in the endpoint in a browser i get the results i expect when i use the endpoint to resolve the query request i get an error, so i started to look at the headers as thats the only thing i can see that changes between a postman request and a normal browser request. for the local wp installation # localhost:8000 looking at the logs i can see the request being made from postman and the browser and axios(used in the query resolver) on the flipside the wp installation thats live on the web the logs show the request from postman and from the browser to the api endpoint but not from the graphql resolver. how do i fix this issue with the resolver not making the request?
this is my resolver for the query
const resolvers = {
Query: {
pages: (_parent, _args, _context) => {
return axios.get(`${wpURL}/wp-json/wp/v2/pages`)
.then(res => res.data)
.catch(error => {
console.log("Response Status:", error.response.status);
console.log("Response Headers:", error.response.headers);
console.log("Response Data:", error.response.data);
});
}
}
}
graphqlserver:
import {ApolloServer} from 'apollo-server-micro'
import Cors from 'micro-cors'
import {schema} from './schema'
const cors = Cors()
const server = new ApolloServer({schema})
const handler = server.createHandler({path: '/api/graphql'})
export const config = {
api: {
bodyParser: false,
}
}
export default cors(handler)
terminal:
> next dev
ready - started server on http://localhost:3000
event - compiled successfully
event - build page: /api/graphql
wait - compiling...
event - build page: /api/graphql
event - compiled successfully
page:
What am i doing wrong?
i figured it out it looks like if the endpoint graphql is fetching data from is not secured via SSL it wont even bother asking for data

Request from Firebase Hosting to Firebase Function blocked by CORS

I'm trying to send push notifications between two devices for a tiny prototype. Both of them are Vue.js apps with firebase SDK integrated, so to implement a push notification flow I deployed a firebase function, but when I call it from any of devices, a CORS error is received as a response.
Both devices (mobile and desktop) have the same client code and knows the token of each other (storage into a firebase real-time database).
The function only uses firebase messaging to send the push notification.
Firebase function:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({ origin: true });
admin.initializeApp();
exports.notification = functions.https.onRequest((req, res) => {
return cors(req, res, () => {
if (req.method === "POST") {
return admin.messaging().send(notification)
.then(result => {
console.log(result);
res.status(200).send("ok")
})
.catch(err => res.status(500).send(err));
} else {
return res.status(400).send("Method not allowed");
}
});
});
Client code:
send(notification, token) {
return fetch("https://[zone]-[project].cloudfunctions.net/notifications", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token, notification })
});
}
And the error is:
Access to fetch at 'https://[zone]-[project].cloudfunctions.net/notifications' from origin 'https://[project].web.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
Could you use The functions.https.onCall trigger?
See https://firebase.google.com/docs/functions/callable .
The Cloud Functions for Firebase client SDKs let you call functions directly from a Firebase app. To call a function from your app in this way, write and deploy an HTTPS Callable function in Cloud Functions, and then add client logic to call the function from your app.
The URI that I used to invoke the function was wrong. It's solved. Sorry about that question.

Enabling CORS in Cloud Functions for Firebase

I'm currently learning how to use new Cloud Functions for Firebase and the problem I'm having is that I can't access the function I wrote through an AJAX request. I get the "No 'Access-Control-Allow-Origin'" error. Here's an example of the function I wrote:
exports.test = functions.https.onRequest((request, response) => {
response.status(500).send({test: 'Testing functions'});
})
The function sits in this url:
https://us-central1-fba-shipper-140ae.cloudfunctions.net/test
Firebase docs suggests to add CORS middleware inside the function, I've tried it but it's not working for me: https://firebase.google.com/docs/functions/http-events
This is how I did it:
var cors = require('cors');
exports.test = functions.https.onRequest((request, response) => {
cors(request, response, () => {
response.status(500).send({test: 'Testing functions'});
})
})
What am I doing wrong? I would appreciate any help with this.
UPDATE:
Doug Stevenson's answer helped. Adding ({origin: true}) fixed the issue, I also had to change response.status(500) to response.status(200) which I completely missed at first.
There are two sample functions provided by the Firebase team that demonstrate the use of CORS:
Time server with date formatting
HTTPS endpoint requiring Authentication
The second sample uses a different way of working with cors than you're currently using.
Consider importing like this, as shown in the samples:
const cors = require('cors')({origin: true});
And the general form of your function will be like this:
exports.fn = functions.https.onRequest((req, res) => {
cors(req, res, () => {
// your function body here - use the provided req and res from cors
})
});
You can set the CORS in the cloud function like this
response.set('Access-Control-Allow-Origin', '*');
No need to import the cors package
For anyone trying to do this in Typescript this is the code:
import * as cors from 'cors';
const corsHandler = cors({origin: true});
export const exampleFunction= functions.https.onRequest(async (request, response) => {
corsHandler(request, response, () => {
//Your code here
});
});
One additional piece of info, just for the sake of those googling this after some time:
If you are using firebase hosting, you can also set up rewrites, so that for example a url like (firebase_hosting_host)/api/myfunction redirects to the (firebase_cloudfunctions_host)/doStuff function. That way, since the redirection is transparent and server-side, you don't have to deal with cors.
You can set that up with a rewrites section in firebase.json:
"rewrites": [
{ "source": "/api/myFunction", "function": "doStuff" }
]
No CORS solutions worked for me... till now!
Not sure if anyone else ran into the same issue I did, but I set up CORS like 5 different ways from examples I found and nothing seemed to work. I set up a minimal example with Plunker to see if it was really a bug, but the example ran beautifully. I decided to check the firebase functions logs (found in the firebase console) to see if that could tell me anything. I had a couple errors in my node server code, not CORS related, that when I debugged released me of my CORS error message. I don't know why code errors unrelated to CORS returns a CORS error response, but it led me down the wrong rabbit hole for a good number of hours...
tl;dr - check your firebase function logs if no CORS solutions work and debug any errros you have
Updated answer: using cors library with Typescript support:
install cors
npm i -S cors
npm i --save-dev #types/cors
index.ts:
import * as cors from "cors";
const corsHandler = cors({ origin: true });
// allow cors in http function
export const myFunction = functions.https.onRequest((req, res) => {
corsHandler(req, res, async () => {
// your method body
});
});
Old answer:
(not working anymore)
Found a way to enable cors without importing any 'cors' library. It also works with Typescript and tested it in chrome version 81.0.
exports.createOrder = functions.https.onRequest((req, res) => {
// browsers like chrome need these headers to be present in response if the api is called from other than its base domain
res.set("Access-Control-Allow-Origin", "*"); // you can also whitelist a specific domain like "http://127.0.0.1:4000"
res.set("Access-Control-Allow-Headers", "Content-Type");
// your code starts here
//send response
res.status(200).send();
});
I have a little addition to #Andreys answer to his own question.
It seems that you do not have to call the callback in the cors(req, res, cb) function, so you can just call the cors module at the top of your function, without embedding all your code in the callback. This is much quicker if you want to implement cors afterwards.
exports.exampleFunction = functions.https.onRequest((request, response) => {
cors(request, response, () => {});
return response.send("Hello from Firebase!");
});
Do not forget to init cors as mentioned in the opening post:
const cors = require('cors')({origin: true});
Update: Any response function that takes time risk a CORS error with this implementation because this doesn't have the appropriate async/await. Don't use outside of quick prototyping endpoints that return static data.
This might be helpful.
I created firebase HTTP cloud function with express(custom URL)
const express = require('express');
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
const main = express();
app.post('/endpoint', (req, res) => {
// code here
})
app.use(cors({ origin: true }));
main.use(cors({ origin: true }));
main.use('/api/v1', app);
main.use(bodyParser.json());
main.use(bodyParser.urlencoded({ extended: false }));
module.exports.functionName = functions.https.onRequest(main);
Please make sure you added rewrite sections
"rewrites": [
{
"source": "/api/v1/**",
"function": "functionName"
}
]
Simple solution using the Google Cloud Console Dashboard:
Go to your GCP console dashboard:
https://console.cloud.google.com/home/dashboard
Go to menu
"Cloud Functions" ("Compute" section)
Select your cloud function, e.g. "MyFunction", a side menu should appear on the right showing you the access control settings for it
Click on "Add Member", type in "allUsers" and select the role "Cloud Function Invoker"
Save it -> now, you should see a remark "Allow unauthenticated" in the list of your cloud functions
Access is now available to everybody from the internet with the correct config to your GCP or Firebase project. (Be careful)
If you don't/can't use cors plugin, calling the setCorsHeaders() function first thing in the handler function will also work.
Also use the respondSuccess/Error functions when replying back.
const ALLOWED_ORIGINS = ["http://localhost:9090", "https://sub.example.com", "https://example.com"]
// Set CORS headers for preflight requests
function setCorsHeaders (req, res) {
var originUrl = "http://localhost:9090"
if(ALLOWED_ORIGINS.includes(req.headers.origin)){
originUrl = req.headers.origin
}
res.set('Access-Control-Allow-Origin', originUrl);
res.set('Access-Control-Allow-Credentials', 'true');
if (req.method === 'OPTIONS') {
// Send response to OPTIONS requests
res.set('Access-Control-Allow-Methods', 'GET,POST','PUT','DELETE');
res.set('Access-Control-Allow-Headers', 'Bearer, Content-Type');
res.set('Access-Control-Max-Age', '3600');
res.status(204).send('');
}
}
function respondError (message, error, code, res) {
var response = {
message: message,
error: error
}
res.status(code).end(JSON.stringify(response));
}
function respondSuccess (result, res) {
var response = {
message: "OK",
result: result
}
res.status(200).end(JSON.stringify(response));
}
If there are people like me out there: If you want to call the cloud function from the same project as the cloud function it self, you can init the firebase sdk and use onCall method. It will handle everything for you:
exports.newRequest = functions.https.onCall((data, context) => {
console.log(`This is the received data: ${data}.`);
return data;
})
Call this function like this:
// Init the firebase SDK first
const functions = firebase.functions();
const addMessage = functions.httpsCallable(`newRequest`);
Firebase docs: https://firebase.google.com/docs/functions/callable
If you can't init the SDK here is the essence from the other suggestions:
If you use firebase hosting and host in the default location, choose rewrites: https://firebase.google.com/docs/hosting/full-config#rewrites
Or use CORS like krishnazden suggested: https://stackoverflow.com/a/53845986/1293220
A cors error can occur if you don't catch an error in a function. My suggestion is to implement a try catch in your corsHandler
const corsHandler = (request, response, handler) => {
cors({ origin: true })(request, response, async () => {
try {
await handler();
}
catch (e) {
functions.logger.error('Error: ' + e);
response.statusCode = 500;
response.send({
'status': 'ERROR' //Optional: customize your error message here
});
}
});
};
Usage:
exports.helloWorld = functions.https.onRequest((request, response) => {
corsHandler(request, response, () => {
functions.logger.info("Hello logs!");
response.send({
"data": "Hello from Firebase!"
});
});
});
Thanks to stackoverflow users: Hoang Trinh, Yayo Arellano and Doug Stevenson
Only this way works for me as i have authorization in my request:
exports.hello = functions.https.onRequest((request, response) => {
response.set('Access-Control-Allow-Origin', '*');
response.set('Access-Control-Allow-Credentials', 'true'); // vital
if (request.method === 'OPTIONS') {
// Send response to OPTIONS requests
response.set('Access-Control-Allow-Methods', 'GET');
response.set('Access-Control-Allow-Headers', 'Content-Type');
response.set('Access-Control-Max-Age', '3600');
response.status(204).send('');
} else {
const params = request.body;
const html = 'some html';
response.send(html)
} )};
Changing true by "*" did the trick for me, so this is how it looks like:
const cors = require('cors')({ origin: "*" })
I tried this approach because in general, this is how this response header is set:
'Access-Control-Allow-Origin', '*'
Be aware that this will allow any domain to call your endpoints therefore it's NOT secure.
Additionally, you can read more on the docs:
https://github.com/expressjs/cors
Cloud Functions for Firebase v2
Cloud Functions for Firebase v2 now allow you to configure cors directly in the HTTP options. It works without the need for any 3rd party package:
import { https } from 'firebase-functions/v2';
export myfunction = https.onRequest({ cors: true }, async (req, res) => {
// this will be invoked for any request, regardless of its origin
});
Beware:
At the time of writing, v2is in public preview.
Only a sub-set of regions is currently supported in v2.
Function names are restricted to lowercase letters, numbers, and dashes.
You can use v1 and v2 functions side-by-side in a single codebase. For improved readability, update your imports to access firebase-functions/v1 or firebase-functions/v2 respectively.
I have just published a little piece on that:
https://mhaligowski.github.io/blog/2017/03/10/cors-in-cloud-functions.html
Generally, you should use Express CORS package, which requires a little hacking around to meet the requirements in GCF/Firebase Functions.
Hope that helps!
For what it's worth I was having the same issue when passing app into onRequest. I realized the issue was a trailing slash on the request url for the firebase function. Express was looking for '/' but I didn't have the trailing slash on the function [project-id].cloudfunctions.net/[function-name]. The CORS error was a false negative. When I added the trailing slash, I got the response I was expecting.
If You are not using Express or simply want to use CORS. The following code will help resolve
const cors = require('cors')({ origin: true, });
exports.yourfunction = functions.https.onRequest((request, response) => {
return cors(request, response, () => {
// *Your code*
});
});
Go into your Google Cloud Functions. You may have not seen this platform before, but it's how you'll fix this Firebase problem.
Find the Firebase function you're searching for and click on the name. If this page is blank, you may need to search for Cloud Functions and select the page from the results.
Find your function, click on the name.
Go to the permissions tab. Click Add (to add user).
Under new principles, type 'allUsers' -- it should autocomplete before you finish typing.
Under select a role, search for Cloud Functions, then choose Invoker.
Save.
Wait a couple minutes.
This should fix it. If it doesn't, do this AND add a CORS solution to your function code, something like:
exports.sendMail = functions.https.onRequest((request, response) => {
response.set("Access-Control-Allow-Origin", "*");
response.send("Hello from Firebase!");
});
If you're testing firebase app locally then you need to point functions to localhost instead of cloud. By default, firebase serve or firebase emulators:start points the functions to server instead of localhost when you use it on your web app.
Add below script in html head after firebase init script:
<script>
firebase.functions().useFunctionsEmulator('http://localhost:5001')
</script>
Make sure to remove this snippet when deploying code to server.
I got the error because I was calling a function that didn't exist on the client side. For example:
firebase.functions().httpsCallable('makeSureThisStringIsCorrect');
Adding my piece of experience.
I spent hours trying to find why I had CORS error.
It happens that I've renamed my cloud function (the very first I was trying after a big upgrade).
So when my firebase app was calling the cloud function with an incorrect name, it should have thrown a 404 error, not a CORS error.
Fixing the cloud function name in my firebase app fixed the issue.
I've filled a bug report about this here
https://firebase.google.com/support/troubleshooter/report/bugs
From so much searching, I could find this solution in the same firebase documentation, just implement the cors in the path:
import * as express from "express";
import * as cors from "cors";
const api = express();
api.use(cors({ origin: true }));
api.get("/url", function);
Link firebase doc: https://firebase.google.com/docs/functions/http-events
If you prefer to make a single handler function (reference answer)
const applyMiddleware = handler => (req, res) => {
return cors(req, res, () => {
return handler(req, res)
})
}
exports.handler = functions.https.onRequest(applyMiddleware(handler))
I'm a very beginner with Firebase (signed up 30 minutes ago). My issue is that I called my endpoint
https://xxxx-default-rtdb.firebaseio.com/myendpoint
Instead of
https://xxxx-default-rtdb.firebaseio.com/myendpoint.json
If you just started with Firebase, make sure you don't forget the .json extension.
I have been trying this for a long time.
It finally finally worked when I made this change.
app.get('/create-customer', (req, res) => {
return cors()(req, res, () => {
... your code ...
The Big difference is that I used cors()(req, res... instead of directly cors(req, res...
It Now works perfectly.
With the same access allow control origin error in the devtool console, I found other solutions with also more modern syntax :
My CORS problem was with Storage (and not RTDB neither the browser...), and then I'm not in possession of a credit card (as requested by the aforementioned solutions), my no-credit card solution was to :
install gsutil :
https://cloud.google.com/storage/docs/gsutil_install#linux-and-macos
to create a cors.json file to be loaded via terminal with gsutil
gsutil cors set cors.json gs://[ your-bucket ]/-1.appspot.com
https://firebase.google.com/docs/storage/web/download-files#cors_configuration
In my case the error was caused by cloud function invoker limit access. Please add allUsers to cloud function invoker. Please catch link. Please refer to article for more info
If none of the other solutions work, you could try adding the below address at the beginning of the call to enable CORS - redirect:
https://cors-anywhere.herokuapp.com/
Sample code with JQuery AJAX request:
$.ajax({
url: 'https://cors-anywhere.herokuapp.com/https://fir-agilan.web.app/gmail?mail=asd#gmail.com,
type: 'GET'
});
See below for how I set up my Express with CORS.
The 'https://pericope.app' is my custom domain for my Firebase project.
It looks like all other answers recommend origin:true or *.
I'm hesitant to allow all origins since it would allow anyone else access to the api. That's fine if you are creating a public service, but if you're doing anything with your data it is risky since it is a privileged environment. For example, this admin SDK bypasses any security rules you have setup for Firestore or Storage.
//Express
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors({
origin: 'https://pericope.app'
}));

Categories

Resources