Handling HSTS in Development

Handling HSTS in Development

Development environments require special consideration:

// Environment-based HSTS
const isDevelopment = process.env.NODE_ENV === 'development';
const isLocalhost = req.hostname === 'localhost' || req.hostname === '127.0.0.1';

app.use((req, res, next) => {
    if (req.secure && !isDevelopment && !isLocalhost) {
        res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
    }
    next();
});

// Development certificate setup
if (isDevelopment) {
    const fs = require('fs');
    const https = require('https');
    
    const options = {
        key: fs.readFileSync('dev-certs/localhost-key.pem'),
        cert: fs.readFileSync('dev-certs/localhost.pem')
    };
    
    https.createServer(options, app).listen(443);
}