22
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.js on HerokuでBasic認証をかける方法

Posted at

Herokuだからどうということはないのですが、環境変数にpasswordを設定できるので、同じコードベースの複数環境を管理したり、不特定多数にコードを共有する場合には便利かと思います。

##環境変数の追加
heroku configコマンドでBasic認証で使うuser nameとpasswordを追加します。
$ heroku config:set BASIC_AUTH_USERNAME="hoge_taro"
$ heroku config:set BASIC_AUTH_PASSWORD="your_password"

##package.jsonに"basic-auth-connect"を追加
Express4からはBasic認証で使う"basic-auth-connect"が外部モジュールになったのでインストールが必要です。

##サンプルコード

server.js
var express = require('express');
var app = express();
var basicAuth = require('basic-auth-connect');

var username = process.env.BASIC_AUTH_USERNAME;
var password = process.env.BASIC_AUTH_PASSWORD;

if (username && password) {
  app.use(basicAuth(username, password));
}

app.use(express.static(__dirname + '/public'));

app.set('port', (process.env.PORT || 5000));

app.listen(app.get('port'), function() {
  console.log("Node app is running at localhost:" + app.get('port'))
})

usernameとpasswordが設定されていない環境ではBasic認証がかからないようにしています。

22
17
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
22
17

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?