Skip to content

Commit cba7f60

Browse files
committed
Add secureRedirect middleware to force production requests to secure protocol
1 parent a7663f9 commit cba7f60

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

middleware/secureRedirect.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
module.exports = (req, res, next) => {
2+
const hosts = [
3+
'pkgstats.com',
4+
];
5+
const proto = req.get('x-forwarded-proto')
6+
? req.get('x-forwarded-proto')
7+
: req.protocol;
8+
const host = req.get('host');
9+
const redirect = proto !== 'https' || hosts.indexOf(host) > -1;
10+
const redirectTo = (hosts.indexOf(host) > -1)
11+
? `https://www.${host}${req.path}`
12+
: `https://${host}${req.path}`;
13+
14+
if (redirect) {
15+
res.redirect(301, `${redirectTo}${req.originalUrl}`);
16+
} else {
17+
next();
18+
}
19+
};

server.js

+7
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,19 @@ const dev = process.env.NODE_ENV !== 'production';
99
const NPMService = require('./src/store/services/NPMService');
1010
const npm = require('./services/npm');
1111

12+
const secureRedirect = require('./middleware/secureRedirect');
13+
1214
const app = nextJS({ dev, dir: './src' });
1315
const handler = routes.getRequestHandler(app);
1416

1517
app.prepare().then(() => {
1618
const server = express();
1719

20+
// Secure redirect
21+
if (!dev) {
22+
server.use(secureRedirect);
23+
}
24+
1825
// Static assets
1926
server.use('/static', express.static(path.join(__dirname, 'src', 'static')));
2027

0 commit comments

Comments
 (0)