0
0

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.

laravel8 jetstream inertia.js環境でapiキーを隠してgitにpushする方法

0
Last updated at Posted at 2021-06-14

前回もapiキーを隠す記事に誤りがあったので修正として
再投稿することにしました。

参考記事

inertia.js公式ドキュメント(共有データ)
https://inertiajs.com/shared-data

実行環境

laravel8, jetstream, inertia.js, vue3 google-maps(npmパッケージ)

実装方法

.envで呼び出す方法としては、
1. .envで MIX_API_KEY=自分のapiキー を記述
2. resources/app.jsでMIX_API_KEYの前にprocess.env.を記述

この2つだけで呼び出し自体はできるが、public/app.jsでコンパイルされる際に
apiキーが漏れてしまう、、、
※私はこれで実際にgoogleからapiキーが漏れていますとメールがきました(笑)

なので、上記の方法とは別の方法で実装します。
今回はgoogle map apiを使うためそのキーで実装しました。

まず、.envにapiキーを記述します。

envファイル.
MIX_API_KEY=自分のapiキー

※MIXをつけることで他のファイルでも呼び出せるようにします。

次に、app/http/middleware/HandleInertiaRequests.phpの
shareメソッドにこのように記述。

HandleInertiaRequests.php
public function share(Request $request)
    {
        return array_merge(parent::share($request), [
            'map_api_key' => env('MIX_API_KEY'),
        ]);
    }

このように記述すると、 .envに指定したMIX_API_KEYをmap_api_keyとして
呼び出せます。

最後に、resources/app.jsにmap_api_keyを呼び出せるようにします。

app.js
require('./bootstrap');

// Import modules...
import { createApp, h } from 'vue';
import { App as InertiaApp, plugin as InertiaPlugin } from '@inertiajs/inertia-vue3';
import { InertiaProgress } from '@inertiajs/progress';
import VueGoogleMaps from '@fawmi/vue-google-maps';

const el = document.getElementById('app');

createApp({
    render: () =>
        h(InertiaApp, {
            initialPage: JSON.parse(el.dataset.page),
            resolveComponent: (name) => require(`./Pages/${name}`).default,
        }),
})
    .mixin({ methods: { route })
    .use(InertiaPlugin)
    .use(VueGoogleMaps, {   // google map api
        load: {
            key: JSON.parse(el.dataset.page).props.map_api_key
        },
    })

    .mount(el);

InertiaProgress.init({ color: '#4B5563' });

これでコンパイルされてもapiキーが漏れるリスクが減ると思います。
漏洩したくない情報を扱うときは慎重にやろうと思いました、、、

0
0
1

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?