Topic: Using .env to hide Emailjs api key

Rosmalina Abrell free asked 3 years ago


Expected behavior Hi guys, I built my react app using the zip download from mdbreact. Everything is working fine and until the part where i need to create a contact form using emailjs. So I created an .env file to hide my user api key in order to use emailjs. I did as many resources told to do: .env in root folder where package.json is, i added REACT_APP_API_KEY:12345myapikey and of course no semicolon or comas behind, also restarting the application after any changes at .env.

Actual behavior But when I tried accessing it on the react file by console logging it, it stays undefined. However If I don't use the .env, and put the userID as string, this can still be recognized and the form is working perfectly fine. Resources (screenshots, code snippets etc.) Currently, this is how my code looks like when using process.env. What actually caused this and what did i miss? do i need to use dotenv?if yes, how do i import and invoke this?

`const userID = process.env.REACT_APP_USER_ID

const Contact = () => {

function sendEmail(e) { e.preventDefault();

emailjs
  .sendForm('Gmail', 'form_template', e.target, userID)
  .then(
    (result) => {
      console.log(result.text);
    },
    (error) => {
      console.log(error.text);
    }
  );
e.target.reset();

}`


Piotr Glejzer staff commented 3 years ago

Are you using only mdbreact or other library/framework like gatsby or nextjs?


Rosmalina Abrell free commented 3 years ago

Hi Piotr, I'm only using mdbreact. Other dependencies I'm using is aos and (now trying to use) emailjs. Basically that's it.


Piotr Glejzer staff commented 3 years ago

did you see this topic?

https://create-react-app.dev/docs/adding-custom-environment-variables/

I don't know what type of app are you using. If you are using cra you can use this topic above, probably it should work with our template too because we are using react-scripts to start a project. If you will use nextjs you have to install it for your own


Danielillo free answered 2 years ago


There's no safe way to store API keys in the front-end. You should add a small backend with nodeJS to handle your key.

You can install the npm module dotenv https://www.npmjs.com/package/dotenv

This will help you use your key the way you are willing to. Hope this gives you a hint.



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue

  • ForumUser: Free
  • Premium support: No
  • Technology: MDB React
  • MDB Version: 5.0.1
  • Device: macOs
  • Browser: Chrome
  • OS: Catalina
  • Provided sample code: No
  • Provided link: No