2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

nuxtjsでfirestoreを使うときのapikeyなどの書き方

Last updated at Posted at 2019-09-20

色々なサイトを見たが書き方が異なっていてだるいので自分のでうまくいった書き方のメモ
自分がMacなのでmacのやり方です。

nuxtはインストールされていて、npx create-nuxt-app , npm run devでサーバーが立てれている前提です。

ではスタート
1、ターミナルで$ npm install -g firebase-toolsします。
これはグローバルにインストールしてしまっているのでもし今回以降使わないのであれば-gを取ってください。

2、firebaseアカウントに接続するために$ firebase loginしてください、この後にfirebaseを使っているアカウントを指定してログインしてください。

3、NuxtでFirebaseを使いたいので、1.のcreate-nuxt-appで作成したNuxtプロジェクトディレクトリのトップでこのコマンドを実行$ firebase initしてください
コマンドを実行するとターミナル上で色々と訊かれます。

? Which Firebase CLI features do you want to setup for this folder? Press Space to select features, then Enter to confirm your choices.

どのサービス使うか

データベース(firestore)とホスティング(Hosting)を選択

? Select a default Firebase project for this directory

どのFirebaseプロジェクトを利用するか
予め作っておいたプロジェクトを選択

? What file should be used for Firestore Rules? (firestore.rules)

データベース(firestore)のルールファイル名は何にするか

? What file should be used for Firestore indexes? (firestore.indexes.json)

データベース(firestore)のインデックスのファイル名

? What do you want to use as your public directory? (public)

FirebaseのHosthingにアップして公開するディレクトリ
Nuxtの場合は静的ファイルの生成がdistディレクトリになるのでdistと入力

? Configure as a single-page app (rewrite all urls to /index.html)? (y/N)

SPA様に設定するか
distのところとファイルを選ぶとこ以外は基本enter押してもらって大丈夫です。

質問が終わるとFirebase関連のファイルが生成されます

firebaserc
firebase.json
firestore.indexes.json
firestore.rules
dist/index.html

4、Firebaseにデプロイ
下記コマンドで、デプロイするディレクトリに指定した./dist内がアップロードされる

$ firebase deploy

ここから紐付けの設定をしていきます。
5、@nuxtjs/dotenvのインストール

$ npm install @nuxtjs/dotenv

Nuxtでdotenvモジュールの使用を設定

nuxt.config.js
modules:[
   '@nuxtjs/dotenv'
],

6、.envファイルにfirebaseの接続情報を記述
.envファイルの作成

$ touch .env

このコマンドで.envファイルが作成されます。

firebaseプロジェクトの設定から>アイコンをクリックして表示される接続情報を.envファイルに設定します。

.env
FB_API_KEY=<FIREBASE_API_KEY>
FB_AUTH_DOMAIN=<FIREBASE_ AUTH_DOMAIN>
FB_DATABASE_URL=<FIREBASE_DATABASE_URL>
FB_PROJECTID=<FIREBASE_PROJECT_ID>
FB_STORAGE_BUCKET=<FIREBASE_ STORAGE_BUCKET>
FB_MESSAGING_SENDER_ID=<MESSAGING_SENDER_ID>

=の右側のところをそれぞれのプロジェクトのapikeyに書き換えてください!!

7、 Nuxtでfirebaseの接続をする
pluginsディレクトリにFirebaseと接続するためのプラグインを作成する
plulginディレクトリにfirebase.jsを作成します。

plugin/firebase.js

import firebase from "firebase";

// .env に設定した値を取得してる
const config = {
  apiKey: process.env.FB_API_KEY,
  authDomain: process.env.FB_AUTH_DOMAIN,
  databaseURL: process.env.FB_DATABASE_URL,
  projectId: process.env.FB_PROJECTID,
  storageBucket: process.env.FB_STORAGE_BUCKET,
  messagingSenderId: process.env.FB_MESSAGING_SENDER_ID
}
if (!firebase.apps.length) {
  firebase.initializeApp(config)
}
export default firebase

nuxt.config.jsにプラグインのパスを追加

nuxt.config.js
plugins: [
    '~/plugins/firebase',
],

Firebaseを使用するページのテンプレートでプラグインを読み込み store/index.js

pages/index.vue
import Vuex from 'vuex'
import firebase from "~/plugins/firebase.js"

nuxt.config.jsにプラグインのパスを書けば自動的に全ページで使えるようになる訳ではなく、 プラグインを使用したいページで都度importする必要があるようです。

8、Cloud Firestoreのデータにアクセス

pages/index.vue
<template>
  <ul>
    <li v-for="(item,index) in init" :key="index">
      {{ item.id }}{{ item.name }}{{ item.email }}
    </li>
  </ul>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  computed: {
    ...mapGetters({
      init: 'getItems'
    })
  }
}
</script>
store/index.js
import Vuex from 'vuex'
import firebase from "~/plugins/firebase.js"


const db = firebase.firestore();
const INIT = 'INIT'

let usersRef = db.collection('users');


const initPlugin = store => store.dispatch(INIT)

const store = () =>
  new Vuex.Store({
    state: {
      itemList: []
    },
    mutations: {
      INIT(state, data) {
        state.itemList = data
      }

    },
    actions: {
      INIT({ commit }) {
        usersRef.get().then(res => {
          let list = []
          res.forEach(doc => {
            let data = {
              id: doc.id,
              name: doc.data().name,
              email: doc.data().email
            }
            list.push(data)
          })
          commit('INIT', list)
        })
      }
    },
    getters: {
      getItems: state => {
        return state.itemList
      }
    },
    plugins: [initPlugin]
  })
export default store

firestoreのところには
コレクション: users
ドキュメント: users
フィールド: email: "test@test.com" name: "test"
が入力してあります。

クラシックモードで書いてあるのは量少なかったからです、nuxt3でなくなるらしいのでnuxt3以降の人はモジュールモードで書いてください、サボってすいません。

もしコピペしてもうまくいかない人はfirestoreのページのルールのところが

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{
      allow read, write: if true;
    }
  }
}

read,writeが許可されているかを確認してみてください、自分の場合は allow read, write: if false;
になっていてエラーが出ました。

最後に

参考にさせていただきました、ほぼ一緒ですが、自分なりにわかりやすく書き直した感じです。
https://chaika.hatenablog.com/entry/2019/01/21/113000

2
5
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
2
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?