Arun Ajay
Arun Ajay

Reputation: 87

If storing my API key in an environment variable is unsafe in React, how do I retrieve this key so I can access my endpoints on AWS API Gateway?

My endpoints on AWS API Gateway require that this key be passed in the header in order for the client to successfully my backend endpoint.

Here's my axios.js file that sets up the axios instances for GET/POST/PUT/DELETE

import axios from 'axios'  
require('dotenv').config()

const API_URL = process.env.REACT_APP_AWS_APIGATEWAY_BASE_URL
const API_KEY = process.env.REACT_APP_AWS_APIGATEWAY_API_KEY


const AxiosInstance = axios.create({
    baseURL: API_URL,  
    headers : {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        'Authorization' : API_KEY,
        'X-API-KEY': API_KEY
    }
});

const getAPI = (apiUrl,params) => AxiosInstance.get(apiUrl,params);

const postAPI = (apiUrl, data,params) => AxiosInstance.post(apiUrl, data,params);

const putAPI = (apiUrl, data,params) => AxiosInstance.put(apiUrl, data,params);

const deleteAPI = (apiUrl,data,params) => AxiosInstance.delete(apiUrl,data,params);

export { 
    postAPI,
    getAPI,
    putAPI,
    deleteAPI,
    API_URL
};
export default AxiosInstance;

Upvotes: 0

Views: 445

Answers (1)

98sean98
98sean98

Reputation: 352

Does your app have users?

If so, you should implement some kind of authentication / authorization logic.

If not, and you allow everyone on the open internet to freely call these api methods, I suppose you can consider building a microservice that will return the API_KEY upon request, and store that in the client's storage (localStorage on browsers, etc.). The microservice can be implemented through an AWS Lambda Function / Firebase Cloud Function, they're pretty cheap to run, and can obviously use environment variables of their own to retrieve the API_KEY from.

Upvotes: 1

Related Questions