Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
OrganizationAdvent CalendarQiitadon (β)
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Cloud Functions で Firebase Dynamic Links を動的に作り、Firestore に入れるとかする

More than 1 year has passed since last update.


公式ドキュメント Firebase Dynamic Links Short Links API Reference を参考に、使いまわせる形で Cloud Functions に helper を置いています。
それの紹介 +α です

Dynamic Links を生成するヘルパー


import * as functions from 'firebase-functions'
import * as request from 'request-promise-native'

export interface DynamickLinkRequest {
  params: DynamicLinkParameters

export interface DynamickLinkRequestResponse {
  shortLink: string
  previewLink: string

export interface DynamicLinkParameters {
  domainUriPrefix: string
  link: string
  iosInfo?: {
    iosBundleId?: string
    iosFallbackLink?: string
    iosAppStoreId?: string
  androidInfo?: {
    androidPackageName?: string
    androidFallbackLink?: string
    androidMinPackageVersionCode?: string
  socialMetaTagInfo?: {
    socialTitle?: string
    socialDescription?: string
    socialImageLink?: string
  analyticsInfo?: {
    googlePlayAnalytics: {
      utmSource: string
      utmMedium: string
      utmCampaign: string
      utmTerm: string
      utmContent: string
      gclid: string
    itunesConnectAnalytics: {
      at: string
      ct: string
      mt: string
      pt: string

export const createDynamicLink = async (req: DynamickLinkRequest): Promise<DynamickLinkRequestResponse> => {
  const requestParams = {
    dynamicLinkInfo: {
      domainUriPrefix: req.params.domainUriPrefix,
      link: req.params.link,
      iosInfo: req.params.iosInfo,
      androidInfo: req.params.androidInfo,
      socialMetaTagInfo: req.params.socialMetaTagInfo,
      analyticsInfo: req.params.analyticsInfo
    suffix: {
      option: 'SHORT'

  const options: request.Options = {
    uri: `https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=${functions.config().api.key}`,
    method: 'POST',
    headers: {
      'content-type': 'application/json'
    json: JSON.parse(JSON.stringify(requestParams))

  await request(options).catch(err => console.error(err))

Authentication で User が作られたタイミングで生成する例


export const createUserDocument = functions.region('asia-northeast1').auth.user().onCreate(async (snapshot, context) => {
  const functionsConfig = functions.config()
  const response = await createDynamicLink({
    params: {
      domainUriPrefix: functionsConfig.domain.prefix,
      link: `https://${functionsConfig.link.prefix}/user/${user.uid}`,
      iosInfo: {
        iosBundleId: functionsConfig.ios.bundleid
      socialMetaTagInfo: {
        socialTitle: functionsConfig.socialmeta.title,
        socialDescription: functionsConfig.socialmeta.description,
        socialImageLink: functionsConfig.socialmeta.image

  // あとは Firestore のドキュメントにセットするなり色々やる


環境依存の値を functions.config() で取ってきているのがポイントのです。(See: Environment configuration)
ちなみに、cloud functions の config はファイルでのセットには非対応なので、こんな感じでやや強引に対応しています。

# 値の set
firebase use $FIREBASE_FLAVOR

# Ref: https://github.com/firebase/firebase-tools/issues/406#issuecomment-367535223
firebase functions:config:set \
$(jq -r 'to_entries[] | [.key, (.value | tojson)] | join("=")' < environments/firebase/functions_${FIREBASE_FLAVOR}.json)

# 値の確認
firebase functions:config:get

# 値の反映
firebase deploy --only functions
    "link": {
        "prefix": "links"
    "api": {
        "key": "XXX"
    "socialmeta": {
        "image": "https://foo.com/bar.png",
        "title": "Foo",
        "description": "foo"
    "domain": {
        "prefix": "https://foo.com"
    "ios": {
        "bundleid": "com.foo",
        "appStoreId": "XXX"
    "android": {
        "packagename": "com.foo",
        "fallbackLink": "https://foo.com"

なお、prefix"links"カスタムドメインを設定して、Hosting と同じドメインを使っているためです。

"hosting": {
        "predeploy": "predeploy_hosting.sh",
        "postdeploy": "postdeploy_hosting.sh",
        "public": "hosting",
        "appAssociation": "AUTO",
        "rewrites": [
            { "source": "/links/**", "dynamicLinks": true },
            { "source": "**", "destination": "/index.html" }
        "ignore": [

Firebase の Console からは確認できない

現状、Console では Console から作ったものしか確認できない。
分析情報は確認できるが、リンク自体を確認するには API を使うしかない。
https://firebase.google.com/support からリクエスト投げてみよっと..

Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away


No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
Help us understand the problem. What is going on with this article?