Detecting HTTPS in JavaScript
You'll learn how to programmatically detect whether your web app is running over a secure HTTPS connection and enforce secure-only behavior.
Now that you understand the importance of HTTPS and secure cookies, you need to verify in JavaScript whether your page is actually served over HTTPS. This is crucial for enforcing security policies, warning users about insecure connections, or conditionally enabling features that require encryption.
The window.location.protocol API
JavaScript provides window.location.protocol, which returns the protocol scheme of the current URL. It will be either "http:" or "https:" (note the colon).
Here's how to check:
if (window.location.protocol === 'https:') {
console.log('✓ Connection is secure');
// Enable secure features
} else {
console.log('⚠ Connection is NOT secure');
// Warn user or redirect
}
Enforcing HTTPS Redirects
You can automatically redirect users to HTTPS if they arrive via HTTP:
if (window.location.protocol !== 'https:') {
// Redirect to HTTPS version
window.location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
}
Think of this like a bouncer at a secure building: if someone tries to enter through an unsecured entrance, they're immediately redirected to the proper, protected entry point.
Practical Use Cases
- Feature gating: Disable sensitive features on insecure connections
- User warnings: Alert users when forms are submitted over HTTP
- Development detection: Allow HTTP only in local development environments
Key Takeaway: Use window.location.protocol === 'https:' to detect secure connections in JavaScript and enforce HTTPS-only behavior for sensitive operations—it's your client-side security checkpoint.