Express.js を mkdert で https 接続する - Express.js

  • 作成日:
  • 最終更新日:2025/06/25

mkcert のインストール

Windows でmkcertを利用するには、Powershell を起動して以下のコマンドを実行します。

winget install mkcert

# インストールされたかバージョンを確認
mkcert --version

自己認証局、ルート証明書の作成

PowerShell

mkcert --install

完了すると以下のメッセージが表示されます。

Created a new local CA 💥 The local CA is now installed in the system trust store! ⚡️ Note: Firefox support is not available on your platform. ℹ️

新しいローカル CA を作成しました 💥 ローカル CA がシステム トラストストアにインストールされました!⚡️ 注: お使いのプラットフォームでは Firefox はサポートされていません。ℹ️

CA(Certificate Authority)

認証局

証明書が作成されたディレクトリのパスを確認するには、以下のコマンドを実行します。

mkcert -CAROOT

mkcert が作成・インストールしたローカル認証局(CA)をシステムから削除するには、以下のコマンドを実行します。

mkcert --uninstall

SSLサーバー証明書

Webサイトごとの SSLサーバー証明書を作成します。

Express-generatorで作成した場合、bin ディレクトリに移動し、以下のコマンドを実行します。

mkcert localhost

上記のコマンドを実行すると、SSLサーバー証明書 (localhost.pem) 秘密鍵 (localhots-key.pem)が作成されます。

Express のアプリのbin/wwwを以下のように変更します。

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('https:server');
// 以下を削除かコメントアウト
// var http = require('http'); 

const https = require('https'); // 追加
const fs = require('fs'); // 追加

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3111');
app.set('port', port);

// 以下を追加
const options = {
  cert: fs.readFileSync(`./bin/localhost.pem`),
  key: fs.readFileSync(`./bin/localhost-key.pem`)
};

/**
 * Create HTTP server.
 */

// http から https に変更
var server = https.createServer(options, app);

... 省略 ...

接続確認

ブラウザでhttps://localhost:3000で接続できるか確認します。

ブラウザを開いたまま設定してい場合は、一度閉じて開きなおします。