question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Define custom projectId in JS for emulator

See original GitHub issue

[REQUIRED] Environment info

firebase-tools:

  • firebase emulator
  • firebase js sdk 7.8.0
  • firebase cli 7.12.1

Platform:

  • macOS

[REQUIRED] Test case

<script>
document.addEventListener("DOMContentLoaded", function () {
      // this doesnt work
      var firebaseConfig = {
        authDomain: "localhost:5000",
        projectId: "project-name-test"
      };
      // Initialize Firebase
      const app = firebase.initializeApp(firebaseConfig);

      // this works great
      firebase.firestore().settings({
        host: "localhost:5002",
        ssl: false
      })
</script>

[REQUIRED] Steps to reproduce

[REQUIRED] Expected behavior

It would be great to init the app with a custom projectId so that the projectId used in Tests against the emulator can be used in some test html / js interface stuff. I would like to keep all my tests and code using a different projectId just to prevent the issue of someone accidentally running them against the live system. Yes the firestore.rules should prevent any major issues but its still possible one of our developers could use their credentials and bearer token against a live url without realising.

[REQUIRED] Actual behavior

I get “Your API key is invalid, please check you have copied it correctly”

Maybe theres a way to do this already and I just don’t understand. The documentation for all this advanced usage of the local emulator is a little lacking. I spent all day trying to figure out why my GET requests to the emulator were not working:

Locally with emulator: GET http://localhost:8080/emulator/v1/projects/example-project/databases/(default)/documents/user/alice Doesnt work. Response:

Not Found

Only to realise its because the /emulator/ part is only required when you call:

DELETE http://localhost:8080/emulator/v1/projects/example-project/databases/(default)/documents

To clear all documents.

It would be awesome if you could include an example project with tests that also sets up a sane local test environment for everything from auth, cloud functions and firestore calls. 😃

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:4
  • Comments:6 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
samtsterncommented, Feb 13, 2020

@madhavajay thanks for explaining all that.

So if you want to change the projectId with the automatic init scripts, just use the --project flag like this. For example using my project fir-dumpster:

$ firebase --project=fir-dumpster emulators:start

When I curl the init file I get something like this:

$ curl http://localhost:5000/__/firebase/init.js
if (typeof firebase === 'undefined') throw new Error('hosting/init-error: Firebase SDK not detected. You must include it before /__/firebase/init.js');
var firebaseConfig = {
  "projectId": "fir-dumpster",
  "databaseURL": "https://fir-dumpster.firebaseio.com",
  "storageBucket": "fir-dumpster.appspot.com",
  "locationId": "us-central",
  "apiKey": "AIzaSyD3Vh...CPx7vJ20i_KjBPk",
  "authDomain": "fir-dumpster.firebaseapp.com",
  "messagingSenderId": "733...301"
};
if (firebaseConfig) {
  firebase.initializeApp(firebaseConfig);
}

Now let’s say I do this with a totally made up projectID like my-fake-project:

$ firebase --project=my-fake-project emulators:start --only hosting
i  emulators: Starting emulators: hosting
✔  emulators: Emulator hub started at http://localhost:4000
⚠  hosting: Authentication error when trying to fetch your current web app configuration, have you run firebase login?
⚠  hosting: Could not fetch web app configuration and there is no cached configuration on this machine. Check your internet connection and make sure you are authenticated. To continue, you must call firebase.initializeApp({...}) in your code before using Firebase.
i  hosting: Serving hosting files from: public
✔  hosting: Local server: http://localhost:5000
✔  hosting: Emulator started at http://localhost:5000
✔  All emulators started, it is now safe to connect.

You can see the emulators start up just fine but they warn me that they couldn’t fetch a configuration for this project. That makes sense, it’s not real!

When I curl the init script now I can see it doesn’t do anything:

$ curl http://localhost:5000/__/firebase/init.js
if (typeof firebase === 'undefined') throw new Error('hosting/init-error: Firebase SDK not detected. You must include it before /__/firebase/init.js');
var firebaseConfig = undefined;
if (firebaseConfig) {
  firebase.initializeApp(firebaseConfig);
}

So that leaves me to run initializeApp() on my own when my page loads. I don’t need a messagingSenderId or even a storageBucket because none of those things are going to work on this fake project.

I think a good improvement would be for __init.js to automatically point your services at the emulator when possible. I will work on that.

Anyway I hope I have answered your questions! I am going to close this issue, but let me know if you have more and I am happy to discuss.

1reaction
madhavajaycommented, Feb 14, 2020

@samtstern thats really awesome. I knew there must be a way but was having trouble interrogating the dynamic config when using the --project param but didn’t think to just hit the .js end point. Very smart. I agree this would be a great addition to the system to automatically handle the correct connections. Also is there a reason that we need to manually override things like this:

firebase.firestore().settings({
    host: "localhost:8080",
    ssl: false
})
firebase.functions().useFunctionsEmulator("http://localhost:5001")

Seems like it would make more sense to do this as part of the initializeApp config or as you mentioned automatically in __init.js.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Install, configure and integrate Local Emulator Suite - Firebase
Configure Emulator Suite. Port configuration; Project ID configuration; Security Rules configuration; Specifying Java options ; Integrate with your CI system.
Read more >
firebase cannot determine project id - node.js - Stack Overflow
You need to add projectId admin.initializeApp({ credential: admin.credential.applicationDefault(), projectId: `xxx-xxxxxx-xxx`, // this line ...
Read more >
Testing apps locally with the emulator | Cloud Pub/Sub ...
// Use the client as you'd normally do, to create a subscription in this example. SubscriptionName subscriptionName = new SubscriptionName(projectId ...
Read more >
Using Firebase - Expo Documentation
The Firebase JS SDK is a JavaScript library that allows you to interact with Firebase services in your project. It supports services such...
Read more >
Building a REST API with Firebase cloud functions, TypeScript ...
Currently, Firebase SDK supports Node.js 12 and 10. ... With our billing plan upgraded, let's create a Firestore database for our app.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found