Search code examples
firebase-hostingflutter-web

Flutter website on firebase hosting works fine with domain 1 but not domain 2


I am using flutter web to create a website for my buisness. I am hosting it on firebase hosting with the url
https://xspectre-9a3b3.web.app/
Now when I added the new domain
https://xspectre.net
The website does not load in this domain and gives the error

main.dart.js:1 Uncaught SyntaxError: Unexpected token '<'
(index):1 Uncaught (in promise) DOMException: Failed to register a ServiceWorker for scope ('https://xspectre.net/') with script ('https://xspectre.net/flutter_service_worker.js'): The script has an unsupported MIME type ('text/html').

It does not work with https://xspectre-9a3b3.firebaseapp.com/ either. What should I do?

EDIT

I discovered the real error is not the MIME type one since it is in my real project too. The actual error is somehow

Uncaught SyntaxError: Unexpected token '<'

When I open the main.dart.js it shows me different code then it should. It shows me the html files not the main.dart.js code and I think that is what is causing the problem. I dont know how or why the files are different for both the URLs.

**EDIT 2 **

Finally figured out the root problem.
Whenever I try to do firebase init, it goes to initialize the whole flutter directory. This means that it says,

You're about to initialize a Firebase project in this directory:

  C:\FlutterProjects\xspectre

and not

You're about to initialize a Firebase project in this directory:

  C:\FlutterProjects\xspectre\build

Now I need to figure out how to do firebase init and deloy in the /build and not root


Solution

  • The website probably still works for you as it is already cached by the service worker. Try with another browser and it will not work.

    firebase init should be run in the project directory, not in the build directory.

    After that, edit your firebase.json file to look like

    {
      "hosting": {
        "public": "build/web",
        "ignore": [
          "firebase.json",
          "**/.*",
          "**/node_modules/**"
        ],
        "rewrites": [
          {
            "source": "**",
            "destination": "/index.html"
          }
        ],
        "headers": [
          {
            "source": "**",
            "headers": [
              {
                "key": "Cache-Control",
                "value": "no-cache"
              }
            ]
          }
        ]
      }
    }
    

    "public": "build/web" points to the directory where the files for deployment are.

    Now you can do flutter build web and firebase deploy