HTTP APIs with HTTPS Sites
In web development, we often use localhost for prototyping and debugging. However, what if the PM wants to test the website, and you don't have the staging deployment yet (e.g., working on a POC)? And you're working at home, so the PM cannot test on your laptop?
You can use tools like ngrok or Cloudflare Tunnel to share your localhost with others quickly. However, the API calls still happen locally, so when making API requests, you'll see errors like this: Web API Error - This request has been blocked; the content must be served over HTTPS
. It suggests that you're making HTTP API calls from an HTTPS website.
There are a few ways to fix this, and the most effective way is to upgrade your API to HTTPS, but we don't want to spend the time here. We want to make it work as soon as possible. The PM is waiting!
The easiest way is to add a <meta>
in the HTML <head>
.
<head>
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />
</head>
Here, we set the Content Security Policy (CSP) directive as "upgrade-insecure-requests" to tell the browser to upgrade insecure HTTP requests to secure HTTPS requests before making them.
🚨 Don't do this in production. It's meant for local development only (at least for me). Seek to upgrade to HTTPS if possible.
This simple trick allows us to bypass the HTTPS error, and everyone's happy now!