LoginSignup
1
4

More than 1 year has passed since last update.

サーバーレスで動的サイト作成(Firebase Hosting + Cloud Functions + Node.js + Express + EJS)

Last updated at Posted at 2021-02-20

2021/3/4 追記
Firebase Hosting + Cloud Functions + Node.js + Express を構成する手順が、公式ドキュメントに記載されていました。
https://firebase.google.com/docs/hosting/functions

本記事でやること

下記の構成でサーバレスで動的サイトを作成する。

  • Firebase
    • Firebase Hosting
    • Firebase Cloud Functions
  • Node.js
    • Express(フレームワーク)
    • EJS(テンプレートエンジン)
    • Express Generator(雛形の作成)

プロジェクトディレクトリの新規作成から、Firebase へデプロイして動作確認をするところまでを掲載します。
各種ツールはインストールしておいてください。

環境

  • Windows 10
  • Ubuntu(WSL) 18.04.5 LTS
  • npm v6.14.11
  • firebase v9.3.0

事前準備

  1. Firebase コンソールから新規プロジェクト作成する
  2. 料金プランを Blaze (従量制)に変更しておく ※ 使用量に応じて料金が発生するのでご注意ください

手順

新規プロジェクトフォルダを作成

mkdir testapp
cd testapp

Firebase Hosting を初期化

firebase init hosting

# 対話式の質問には下記のように回答してください。
? What do you want to use as your public directory? public
? Configure as a single-page app (rewrite all urls to /index.html)? Yes
? Set up automatic builds and deploys with GitHub? No

public フォルダは必要ないので削除

rm -r public

express-generator で ソースフォルダを作成

# テンプレートエンジンは EJS を使用
express -e functions

npm を初期化

npm init

EJS をインストール

npm install -save ejs

関連パッケージを削除・インストールしておく

npm uninstall debug --save
npm install firebase-functions firebase-admin static-favicon morgan cookie-parser body-parser

app.js を編集

先頭と末尾に下記を追加

app.js
const functions = require('firebase-functions');
中略
module.exports.func_https = functions.https.onRequest(app);

firebase.json を編集

firebase.json
{
    "hosting": {
        "public": "functions",
        "ignore": [
            "firebase.json",
            "**/.*",
            "**/node_modules/**"
        ],
        "rewrites": [
            {
                "source": "**",
                "function": "func_https"  これに変更
            }
        ]
    },
    "functions": {               以下の3行を追加
        "runtime": "nodejs12"    追加
    }                            追加
}

ローカル環境で動作確認

Firebase エミュレータを実行して動作確認する

firebase emulators:start

localhost にアクセスして下記画像のようになればOK
エミュレータ起動確認.PNG

Firebase へデプロイ

firebase deploy -i

Webコンソールで Hosting と Cloud Functions を確認すると、データがアップされています。

Hosting でURLを確認してアクセス
Hostingで確認.PNG
無事デプロイができました!

参考にさせていただいた記事

【Firebase】Cloud Functions + Express + EJSで動的コンテンツを配信する
大変参考になりました。ありがとうございました。

1
4
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
1
4