LoginSignup
5
3

More than 3 years have passed since last update.

Next.jsをSSRでFirebaseデプロイ

Posted at

はじめに

next.jsをSSR(サーバーサイドレンダリング)でデプロイをしようと思い、
思いのほか、手間取ったので、ここでアウトプットしておきまーす!

next.jsをSSG(static generation)静的ビルドする場合はnext exportでoutディレクトリで良かったのですが、

SSRする場合は、cloud functionsをつかって、サイトアクセス時にHTMLを生成しないといけないようです!

デプロイまで

まずいつも通り

firebaseのコンソールでプロジェクトを作成しておいてください!

npx create-next-app your app
cd your app
//firebaseをグローバルインストールしていない方は
npm install -g firebase-tools
firebase login
firebase init 
//ここではhostingとfunctionsのみ選択そして既存のプロジェクトIDを選択

buildディレクトリ設定

module.exports = {
  distDir: "./.next",
};

今回はserver-side-renderingなのでbuildファイルは、.nextディレクトリになります!

firebase周りの設定

.firebaserc
{
  "projects": {
    "default": "your-projectId"
  }
}
firebase.json
{
  "hosting": {
    "public": "public",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      {
        "source": "**",
        "function": "nextjsFunc"
      }
    ]
  },
  "functions": {
    "source": "./functions/",
    "predeploy": [
      "npm --prefix \"$PROJECT_DIR\" install",
      "npm --prefix \"$PROJECT_DIR\" run build"
    ],
    "runtime": "nodejs10"
  }
}

functionsのパスを設定
predeployでデプロイ前installとbuildをデフォルトで行うようにする

cloud functions関数作成

functions/index.js
const { https } = require("firebase-functions");
const { default: next } = require("next");

const isDev = process.env.NODE_ENV !== "production";
const nextjsDistDir = require("./next.config.js").distDir;

const nextjsServer = next({
  dev: isDev,
  conf: {
    distDir: nextjsDistDir,
  },
});
const nextjsHandle = nextjsServer.getRequestHandler();

exports.nextjsFunc = https.onRequest((req, res) => {
  return nextjsServer.prepare().then(() => nextjsHandle(req, res));
});

これで

firebase deploy --only functions,hosting

サーバーサイドレンダリングのデプロイが完了

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