All tutorials

Hiding your API Key

intermediate

One of the most common uses of the what3words API is within browser-based applications. For example, you might be using the what3words AutoSuggest Component to allow easy capture of 3 word addresses on your website. In cases like these, where a client-side JavaScript application is making calls to the public what3words API, there is a danger that your API key will be both visible inside your JavaScript application, and over the network.

To mitigate against this, you can hide your API key by proxying API calls through a proxy application running on your server.

1Setup

The example provided on the code tab is written in PHP. While no PHP dependencies are required, it is assumed that you have a working environment to host PHP from.

You will need a what3words API key, which should be assigned to the $base_url variable. If you don’t already have an API key, you can obtain one by registering for an account.

2Usage

Assuming you have the above PHP script running on your webserver, in a file called w3w_proxy.php, you should be able to call it with any valid what3words API HTTP GET request. For example, to make a convert-to-coordinates call, you could make the following HTTP request:

https://<domain>/w3w_proxy.php/convert-to-coordinates?words=index.home.raft
Copied
3CORS

It is important that efforts are taken to make sure other websites are not able to make use of your proxy.

By default, web browsers permit scripts contained in a first web page to access data from a second source, but only if both sources have the same origin. Therefore, by default, only web pages served from the same domain as your proxy will be able to make successful AJAX through the proxy.

If however, you are hosting your proxy on a different domain to your website, you will need to add the Access-Control-Allow-Origin header (with the value of your websites domain) to your proxies response headers. This allows the browser to access your resource (the proxy), even though the request is coming from a different domain. The following code snippet demonstrates how this can be achieved:

$allowed_origin = 'example.com';
header('Access-Control-Allow-Origin:' . $allowed_origin);
Copied
Server and ScriptingWebsiteAdd a 3 word address input fieldUse 3 word addresses with a mapUse 3 word addresses within an address searchAndroidJavaJavaScriptObjective-CPHPPythonSwift

Related tutorials