Search code examples
javascriptphpajaxlaravellaravel-5.3

How to retrieve API key safely from .env file into javascript View - Laravel


I have the key placed safely in .env file and I would like to make an ajax request to a paid API service. I have the Javascript file (containing ajax code) which is in public/ajax.js

I can retrieve in this way, put this line of code : $key = env('SECRET_API_KEY'); in controller and pass it to javascript directly using https://github.com/laracasts/PHP-Vars-To-Js-Transformer but then I am forced to put @include('footer') in some X page. So, when I check the source I see my API key :/

I am able to pull the data successfully but How to prevent this?

my current url : url:"http://johndoe?param1=abc&param2=def&_token="+key, in Ajax code.

If I directly put this in javascript $key = env('SECRET_API_KEY'); I get an error Uncaught ReferenceError: env is not defined

What is the best approach to retrieve api key?


Solution

  • Define a route that your JS will call, from that route, define a controller and function that will handle the request and make the API call to the paid service.

    Route::get('api-call', 'APIController@call');
    
    //APIController
    //use GuzzleHttp\Exception\GuzzleException;
    //use GuzzleHttp\Client;
    ...
    
    public function call(Request $request)
    {
        $params = $request->all();
    
        $api_key = env('SECRET_API_KEY');
        $url = 'url-to-paid-service?' . $params . '&key=' . $api_key; 
        $client = new Client();
        $res = $client->get($url);
    
        return response()->json($res->getBody());
    }
    

    From your ajax, make the call http://your-own-site/api-call