PHP Middleware for Keeping Your JS API Secrets Secret

Screenshot of a design context website where the weather data is being pulled via API.

Screenshot of a design context website where the weather data is being pulled via API.

Origin Story

We were looking to pull in live weather data for a eco-related design contest that VCU Qatar is hosting. I found a free API for weather but wanted a way to use it via javascript and not expose any secrets. That led to the script below.

Many APIs have query strings that require app IDs or other authentication elements you’d rather not have exposed to the public. Even if you can restrict access to your own sites, you might still want a bit more privacy.

In this scenario PHP acts as middleware and only returns the public data while hiding all the secrets.

Line #1 tells us which API endpoint and parameters we’re using.
Line #2 gets the data from our API with our fully authenticated URL.
Line #3 tells the browser that the page we’re making is JSON and it should treat it accordingly.
Line #4 lets other sites access the data. You can learn more about some CORS options over here.
Line #5 spits the data back out.

$weather_data_url = 'http://api.openweathermap.org/data/2.5/forecast?id=290030&APPID=MY_SECRET_CODE_WENT_HERE&units=metric&lang=ar';
$json = file_get_contents($weather_data_url);
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");//you could be more restrictive but I was being lazy
echo $json;

2 thoughts on “PHP Middleware for Keeping Your JS API Secrets Secret

Comments are closed.