Skip to content

Commit b74cdad

Browse files
committed
move https redirection into its own middleware
1 parent a665737 commit b74cdad

File tree

4 files changed

+25
-16
lines changed

4 files changed

+25
-16
lines changed

config/index.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,8 @@ module.exports = {
4343

4444
serverResolvePaths: {
4545
api: 'server/api',
46-
constants: 'common/js/constants'
46+
constants: 'common/js/constants',
47+
middleware: 'server/middleware'
4748
},
4849

4950
// Isomorphic configuration

server/middleware/httpsRedirect.js

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import url from 'url';
2+
3+
export default function ({ enabled = false }) {
4+
return function(req, res, next) {
5+
if (enabled && !req.secure) {
6+
const secureUrl = url.resolve(`https://${req.headers.host}`, req.url);
7+
return res.redirect(secureUrl);
8+
}
9+
10+
return next();
11+
};
12+
}

server/middleware/index.js

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { default as httpsRedirect } from './httpsRedirect';

server/server.js

+10-15
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,16 @@ import compression from 'compression';
55
import Api from './api';
66
import cookieParser from 'cookie-parser';
77
import ReactRenderer from './renderer';
8+
import { httpsRedirect } from 'middleware';
89

910
const env = process.env.NODE_ENV || 'development';
10-
let app = new express();
11+
const app = new express();
1112

1213
// Secure with helmet
1314
app.use(helmet());
1415

15-
/* Ensures SSL in used in production. To use, uncomment the below.
16-
app.use(function (req, res, next) {
17-
var sslUrl;
18-
19-
if (env === 'production' && req.headers['x-forwarded-proto'] !== 'https') {
20-
sslUrl = [process.env.APPLICATION_BASE_URL, req.url].join('');
21-
return res.redirect(sslUrl);
22-
}
23-
24-
return next();
25-
});
26-
*/
16+
// Ensures SSL in used in production.
17+
app.use(httpsRedirect({ enabled: env === 'production' }));
2718

2819
// parse cookies!
2920
app.use(cookieParser());
@@ -32,14 +23,18 @@ app.use(cookieParser());
3223
app.use(compression());
3324

3425
// Add middleware to serve up all static files
35-
app.use('/assets',
26+
app.use(
27+
'/assets',
3628
express.static(path.join(__dirname, '../' + process.env.PUBLIC_OUTPUT_PATH)),
3729
express.static(path.join(__dirname, '../common/images')),
3830
express.static(path.join(__dirname, '../common/fonts'))
3931
);
4032

4133
// handle browsers requesting favicon
42-
app.use('/favicon.ico', express.static(path.join(__dirname, '../common/images/favicon/favicon.ico')));
34+
app.use(
35+
'/favicon.ico',
36+
express.static(path.join(__dirname, '../common/images/favicon/favicon.ico'))
37+
);
4338

4439
// Mount the REST API
4540
app.use('/api', Api);

0 commit comments

Comments
 (0)