LoginSignup
3
2

More than 3 years have passed since last update.

Next.js + Firebase Hosting + SSR 環境でBasic認証をかける

Last updated at Posted at 2020-04-01

概要

Next.js + Firebase Hosting + SSR 環境でBasic認証をかけようという記事。

Next が持っているメソッドだけでは対応できなかったので、Express も使用します。

また、Next.js + Firebase Hosting + SSR 環境については、
with-firebase-hosting-and-typescript こちらのテンプレートを利用します。

Firebase を利用する関係上 node.js のバージョンは10系を使用します。
firebase-toolsは最新を使用しましょう。

手順

Next.js + Firebase Hosting + SSR 環境のセットアップ

README.md を参考にセットアップしてみてください。

yarn create next-app --example with-firebase-hosting-and-typescript with-firebase-hosting-and-typescript-app

モジュールのインストール

  • express
  • @types/express
  • next-routes
  • basic-auth-connect
yarn add express next-routes basic-auth-connect
yarn add -D @types/express

実装

Express 側でベーシック認証を通して、 Next のアプリに流します。

src/functions/index.ts
import * as functions from 'firebase-functions';
import next from 'next';
import express from 'express';

/* eslint-disable @typescript-eslint/no-var-requires */
const routes = require('next-routes');
const basicAuth = require('basic-auth-connect');

const USERNAME = 'user';
const PASSWORD = 'password';

const server = express();

const app = next({ dev: false, conf: { distDir: 'next' } });
const handler = routes().getRequestHandler(app);
server.use(basicAuth(USERNAME, PASSWORD));
server.get('*', (req, res) => handler(req, res));

export const nextApp = functions.https.onRequest(server);

Firebase Project の設定

<project-name-here> こちらを自身のプロジェクト名に変更します。

{
  "projects": {
    "default": "<project-name-here>"
  }
}

実行

localで実行

firebase-emulators を使ってローカルでもBasic認証の確認ができます。

Build

yarn preserve

Run

firebase emulators:start

デプロイ

firebase deploy

以上 ☺️

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