Daniel
Daniel

Reputation: 15

Best way to secure an API key in Vanilla JS and Django

I am building a simple webapp in Django which makes use of Google Places API. The API is called from main.js file, and the data is displayed on the page.

Right now, the main.js file looks like this:

...
const apikey_gmaps = "AIzaSyDMjUwEt0bumPTVt1GpfQHrxyz";
var lat = position.coords.latitude;
var long = position.coords.longitude;
fetch("https://maps.googleapis.com/maps/api/geocode/json?latlng="+lat+","+long+"&key="+**apikey_gmaps**)
  .then(...
...

I want to secure the API key, since I don't want everyone to be use and share my credentials, and break my bank. I have been reading about it lately, and I am able to use .env file in Django(Python) using the Decouple library. I want to use the .env variables in the main.js file. The only solution that I could find was to use dotenv, but that requires NodeJS.

Is there any way to pass the API key from .env to Django and then from Django to main.js? Is there a better way of achieving this?

Upvotes: 1

Views: 1040

Answers (1)

Danish Shakeel
Danish Shakeel

Reputation: 227

You can't secure it if you are calling it from the client-side. What you need to do is create a view to abstract the key.

In views.py:

from rest_framework.decorators import api_view, renderer_classes
from rest_framework.renderers import JSONRenderer, TemplateHTMLRenderer
from rest_framework.response import Response
import requests

@api_view(('GET',))
@renderer_classes([JSONRenderer])
def gmapAPI(request):
    lat = request.GET.get('lat', 'default_fb_value')
    long = request.GET.get('long', 'default_fb_value')
    apikey_gmaps = "#KEY_OR_GET_FROM_ENV";

    url = f'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={lat},{long}&rankby=distance&key={apikey_gmaps}'
    r = requests.get(url)

    print(r.json())
    return Response(r.json())

In urls.py add:

...
path('maps_api/', views.gmapAPI, name='maps_api'),
...

In main.js:

    ...
var lat = position.coords.latitude;
var long = position.coords.longitude;
var targetUrl = (`website/maps_api/?lat=${lat}&long=${long}`) 
fetch(targetUrl)
  .then(...
...

Please note that this will make the process of digging up the key very difficult, but the key will still be discoverable, and a good/bad hacker can still get it.

Upvotes: 1

Related Questions