LoginSignup
53
12

More than 1 year has passed since last update.

Firebase Functionでregionを指定するとHostingのrewritesがうまくいかない件

Last updated at Posted at 2019-03-01

タイトルままですが...

Function

Functionを書きます。 .region('asia-northeast1') を指定することで、us-central1とかではなくasia-northeast1で動きます。

exports.Sample = functions
  .region('asia-northeast1')
  .https.onRequest((request, response) => {
        response.status(200).send('Hello Fireabase');
  });

https://asia-northeast1-hogehoge.cloudfunctions.net/Sample で動くようになります。

firebase.json

Hostingのrewritesは下記のようにします。

https://hogehoge.firebaseapp.com/functions/Sample を呼ぶとSampleが稼働するはずです。

{
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "hosting": {
    "public": "app",
    "rewrites": [
      {
        "source": "/functions/Sample",
        "function": "Sample"
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ],
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}

実際は...

転送されるのはいいんですが、こんな感じになっちゃいました...
asia-northeast1ではなくus-central1になっちゃいます。

https://us-central1-hogehoge.cloudfunctions.net/Sample/functions/Sample にリダイレクトされてしまいます。

どうすればいいんだろ...?

firebase.jsonの指定でなんとかなるのかもしれませんが、hosting の完全な構成の例には書いてないような。

だいぶ経ちますができないみたいです (2022-08-19更新)

ここに記載がありました。

重要: HTTP 関数を使用して Firebase Hosting で動的コンテンツを提供するには、us-central1 を使用する必要があります。

アプリから使うならonCall〜httpsCallableにしよう。

Webアプリ等から利用するなら、fetchとかではなくonCallを使えばCORSや認証関係などの面倒なことが楽に回避できます。

Cloud Functionsの方はこんな感じになります。

regionを指定します。

exports.doSomeAction = functions
  .region('asia-northeast1')
  .https.onCall(async (data, context) => {
    if (!context || !context.auth) {
      throw 'permission denied , The resource cannot be accessed. Authentication is required.';
    }
    return true;
  });

クライアント側はこんな感じになります。

こちらもregionを指定します。

const doSomeAction = () => {
  const callable = firebase
    .app()
    .functions('asia-northeast1')
    .httpsCallable('doSomeAction');
  return callable({});
};

export default {
  doSomeAction: doSomeAction
};
53
12
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
53
12