LoginSignup
4
2

More than 5 years have passed since last update.

Firebase(Angularfire2)でビルドした時だけinvalid-api-keyエラーが出る場合

Posted at

ng serveで動作している際は問題なく、buildしてそこから起動すると以下のようなエラーが出ました。

ERROR Tr {code: "auth/invalid-api-key", message: "Your API key is invalid, please check you have copied it correctly."}
ERROR Error: Uncaught (in promise): Error: Your API key is invalid, please check you have copied it correctly.

D8E6DB7221E95C778BA8A0335903CAB9.png

firebaseの設定も特に問題なくキーなどが間違っているということもありません。
解決には以下のissueがヒントになりました。

Angularfire2ではenvironment.tsにキーを記載するようにドキュメントに書かれているのでその通りに従っています。
なのでenvironment.tsに記述するのですが、HMR用にenvironment.hmr.tsや本番用にenvironment.prod.tsなどと複数のファイルにまたがっていて、同じ記述を複数の箇所にする必要があります。

なので一つのファイルにキーをまとめてそれをimportするようにしていました。

firebase.ts
export default {
  apiKey: "xxx-xxx",
  authDomain: "xxx.firebaseapp.com",
  databaseURL: "https://xxx.firebaseio.com",
  projectId: "xxx",
  storageBucket: "xxx.appspot.com",
  messagingSenderId: "xxx"
};
environment.ts
import firebase from './firebase';

export const environment = {
  production: true,
  hmr: false,
  firebase
};

このようにしていたのですがこれだと前述したエラーが発生しました。

ネットワークのリクエストを見る感じFirebaseへリクエストをかけて認証が弾かれたのでエラーを出しているという感じではなく一切のリクエストをせずにエラーが出ているようでした。
何らかの静的解析で弾かれているだろうということで、一旦importではなく直接以下のように変更したところ問題なく動作するようになりました。

environment.ts
import firebase from './firebase';

export const environment = {
  production: true,
  hmr: false,
  firebase: {
    apiKey: "xxx-xxx",
    authDomain: "xxx.firebaseapp.com",
    databaseURL: "https://xxx.firebaseio.com",
    projectId: "xxx",
    storageBucket: "xxx.appspot.com",
    messagingSenderId: "xxx"
  }
};

調べにくく結構何時間もハマりました

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2