LoginSignup
68
56

More than 5 years have passed since last update.

Nuxt.jsでlocalhostをSSL化する方法

Posted at

解決したいこと

Facebookのログイン機能を実装するときに、OAuth設定で、HTTPSが強制されていました。
ローカルで開発する時に少し困ったので、
今回はNuxt.jsでlocalhostをSSL化する方法を紹介します。

以下のように「HTTPSを強制」をOFFに出来ない...
スクリーンショット 2019-03-29 13.53.17.png

解決方法

解決する為に、今回はmkcertを使ってSSL証明書を発行しました。
mkcertはLocalCAの作成と証明書の発行が簡単に出来るツールです。
mkcertを使うことで、ブラウザで警告を出さずにSSL化することが出来ます。
主な流れは以下の通りです。

  1. mkcertをインストール
  2. mkcertでLocalCAを作る
  3. mkcertで証明書を作成
  4. 作った証明書を読み込んでNuxtを起動

SSL証明書の発行まで

mkcertのインストール

$ brew install mkcert

LocalCAを作る

$ mkcert -install

localhostに対してSSL証明書を発行

$ mkcert localhost
Created a new certificate valid for the following names 📜
 - "localhost"

The certificate is at "./localhost.pem" and the key at "./localhost-key.pem"

これで証明書を作ることが出来ました。

Nuxtをhttpsで起動する

今回変更するファイル群は以下の通りです。
既存のserver/index.jsを汚したくなかったので、server/localhost/index.jsを新たに作成しました。
mkcertで作った証明書もserver/localhost/に移動しておきます。

server/
  ┣ localhost/
    ┣ index.js
    ┣ localhost.pem      // mkcertで作ったcert
    ┣ localhost-key.pem  // mkcertで作ったkey
package.json

起動スクリプトの作成

server/localhost/index.js
const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
const https = require('https')
const fs = require('fs')

// Import and Set Nuxt.js options
const config = require('../../nuxt.config.js')

async function start() {
  // Init Nuxt.js
  const nuxt = new Nuxt(config)

  const { host, port } = nuxt.options.server

  try {
    const builder = new Builder(nuxt)
    await builder.build()
  } catch(error) {
    console.error(error)
    return false
  }

  // https config
  const https_options = {
    key : fs.readFileSync(`${__dirname}/localhost-key.pem`),
    cert: fs.readFileSync(`${__dirname}/localhost.pem`),
  }

  // Give nuxt middleware to express
  app.use(nuxt.render)

  // Listen the server
  https.createServer(https_options, app).listen(port, host)
  consola.ready({
    message: `Server listening on https://${host}:${port}`,
    badge: true
  })
}
start()

package.jsonの修正

package.json
{
  "scripts": {
    "dev": "cross-env NODE_ENV=development nodemon server/localhost/index.js --watch server",
   }
}

サーバー起動と動作確認

$ npm run dev
READY  Server listening on https://localhost:3000

ブラウザでhttps://localhost:3000にアクセス。

スクリーンショット 2019-03-29 11.47.38.png

無事、警告も出ずhttps化することが出来ました。

68
56
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
68
56