Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access enviroment variables from laravel to react

I have a laravel 5.7 project which uses react for front-end and google maps. I'm trying to access a .env variable to a react component. with this code i have the following error message :

Google Maps JavaScript API error: InvalidKeyMapError

My api key is working and google map loads if i just set it like key: "edfefefe", but i wanted a safer way to do it...can someone explain me what i'm missing?

PS i have already installed dotenv

//my .env file
GOOGLE_MAP_KEY=edfefefe
//my react component

import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';
import './Map.css';

class Map extends Component {
    render() {
    let center = {
    lat: 41.083538,
    lng: 23.558191
    }
        return (
            <div className="map-panel">
        <GoogleMapReact
          bootstrapURLKeys={{ key: process.env.GOOGLE_MAP_KEY }}
          defaultCenter={center}
          zoom={16}
        >
        </GoogleMapReact>
      </div>
        );
    }
}

export default Map; 


like image 394
daenerysTarg Avatar asked Jan 31 '19 00:01

daenerysTarg


People also ask

How do I get an environment variable in React?

You can access it from process. env. NODE_ENV . This variable changes based on what mode you are currently in.


Video Answer


1 Answers

You must prefix env variables with MIX_ if you want them available on the front end. You definitely don't want the front end reading all of your environmental variables. See https://laravel.com/docs/5.7/mix#environment-variables

There really isn't any extra safety with this method, it just gives you an easier ability to swap out keys in different environments.

like image 67
Devon Avatar answered Oct 26 '22 22:10

Devon