1

So I have an API_KEY which I'm storing in .env file, and using javascript template I had no problems accessing .env file. But now I'm using a typescript template and I want to know how can I use variables from .env file.

It looks like this:

API_KEY={myapikey}
API_BASE={api_base}

And that's the way I access it in a redux slice:

const API_BASE = process.env.API_BASE;
const TMDB_API_KEY = process.env.API_KEY;

And then I fetch data using redux thunk:

export const fetchPopular = createAsyncThunk('popular/fetchPopular', async () => {
  const response = await axios.get<MovieResults>(`${API_BASE}movie/popular?api_key=${TMDB_API_KEY}`);
  console.log(response.data);
  return response.data.results;
})

But in the end it returns me undefined, although when I declared api key and api base directly everything was alright.

Edit: I had dot-env installed and now I imported it in my index.tsx using:

require('dotenv').config()
console.log(process.env)

And now I have next errors: enter image description here

9
  • 1
    Prefix them? See create-react-app.dev/docs/adding-custom-environment-variables Commented Jun 6, 2022 at 13:09
  • Do you have dotenv installed, or a package that depends on it (like react-dotenv)? npmjs.com/package/dotenv Commented Jun 6, 2022 at 13:15
  • @jonrsharpe hi! i prefixed them but it didn't solve the problem Commented Jun 6, 2022 at 13:19
  • Then please edit to give a minimal reproducible example that follows the guidance. Commented Jun 6, 2022 at 13:20
  • @jonrsharpe i edited my original question and added more details Commented Jun 6, 2022 at 13:27

1 Answer 1

5

I figured out the problem. The first commenter said that I should prefix my variables adding REACT_APP_ before them and I did it but nothing happened. Then I read in the documentation he sent that I need to restart the development server after prefixing the variables and it worked. So after prefixing the variables you need to re-run the server with npm start.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes. You don't need additional package to handle .env in React project. Just prefix the variable with REACT_APP and it will be available via process.env

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.