0

I need to implement a reCAPTCHA system in my React application. So, I registered the development and production domains with Google reCAPTCHA. I created two .env files, one .env.development.local and one .env.production.local in which I added the keys received during configuration. Please help me because it is not very clear to me what exactly needs to be done next. As far as I understand, I have to install the dotenv library, but further I don't know how to make the application use the keys depending on the environment in which it runs.

Is this ok?

index.js

import dotenv from 'dotenv';

dotenv.config();

export const RECAPTCHA_SITE_KEY =
  process.env.NODE_ENV === 'development'
    ? process.env.REACT_APP_RECAPTCHA_KEY_DEV
    : process.env.REACT_APP_RECAPTCHA_KEY_PROD;

Do I have to add something in package.json?

Thanks!

1
  • what is the error that you are facing? Commented Mar 14, 2023 at 10:04

2 Answers 2

0

I recommend defining a dev env file for local development. For example - VARIABLES_DEV.env

Inside that, include the following:

REACT_APP_RECAPTCHA_KEY_DEV ="YOUR_KEY"

And then in your application, do the following

import dotenv from 'dotenv';

dotenv.config();

export const RECAPTCHA_SITE_KEY =
  process.env.NODE_ENV === 'development'
    ? process.env.REACT_APP_RECAPTCHA_KEY_DEV
    : process.env.REACT_APP_RECAPTCHA_KEY_PROD;

For the actual Production key, store it in your env config in your deployment server. For example, if you were using Vercel, you can define Env variables to use during deployment. Its best not to leave a file for Production.

2
  • but how will NODE_ENV will be setted? i know that by default it is "development", but how it will be setted to production? do I have to add something in package.json?
    – alexsmt
    Commented Mar 14, 2023 at 10:28
  • if you were deploying vercel, you can set it through vercel. where are you deploying it on? i could send you some links Commented Mar 15, 2023 at 11:03
0

I assume your issue with the set key is as per the environment.

There is a very simple way to to that:

Step one: Go to the root folder of your application and create a text file called .env.

Step two: Create your custom variables in the new file. Create React App(CRA) enforces the prefix REACT_APP on every custom variable. Please note that variables without the prefix are ignored during bundling.

REACT_APP_NODE_ENV =dev
REACT_APP__DEV_KEY=aaddddawrfffvvvvssaa

Step three: Assign them to variables, print them to the screen etc, but they are read-only from your Javascript file.

console.log(process.env.REACT_APP_NODE_ENV ); 

Not the answer you're looking for? Browse other questions tagged or ask your own question.