FirebaseHosting + CloudFunctionsでクライアントのIPを取得する方法


複雑な家庭の事情でどうしてもfirebaseを使いつつクライアントのIPアドレスを取得しなくてはならなかったのでメモ。

前提として、フロントはNUXTでつくってます。

バックエンド(CloudFunctions側)

/functions/index.js
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);

exports.getIp = functions.https.onCall((data, context) => {
  const clientIp = context.rawRequest.headers['x-appengine-user-ip'];
  return clientIp;
});
  • firebase内でのリクエストなのでfunctions.https.onCall()を使用
  • onCall((data, context)
    • dataにはリクエスト時に投げた値が入りますが、今回は何も投げません
    • contextにはリクエストする側の認証情報が入ります
    • 詳しくは公式説明で
  • context.rawRequest.headers['x-appengine-user-ip']でIPが取得できます
  • リクエストヘッダーの値についての詳しい情報も公式説明で

フロントエンド(NUXT側)

/pages/index.vue
  created() {
    const getIp = firebase.functions().httpsCallable("getIp");
    getIp().then((response) => {
      console.log(response)
    });
   },
  • httpsCallableで関数を指定
  • ページ読み込んだらすぐに確認できるようcreatedに書いてます