Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Api key doesn't work when i import it from .env, but works when i use it directly

I’ve started my project with Vite.

When I directly use my api key instead of importing it from .env, it works. But when I use it like this I get the error below on the console.

{status_code: 7, status_message: ‘Invalid API key: You must be granted a valid key.’, success: false}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s my code

const apiKey = import.meta.env.REACT_APP_API_KEY;

  const getMovies = () => {
    fetch(`https://api.themoviedb.org/3/discover/movie?api_key=${apiKey}`)
      .then((res) => res.json())
      .then((json) => console.log(json))
      .catch((err) => console.log(err));
  };

  useEffect(() => {
    return () => {
      getMovies();
    };
  }, []);

>Solution :

It seems that you are trying to access an environment variable from your .env file using import.meta.env.REACT_APP_API_KEY. However, according to the Vite documentation, only environment variables prefixed with VITE_ are exposed to your Vite-processed code. To access your API key, you should prefix it with VITE_ in your .env file and then access it using import.meta.env.VITE_REACT_APP_API_KEY. For example, in your .env file, you should have something like this:

VITE_REACT_APP_API_KEY=your_api_key

And then in your code, you can access it like this:

const apiKey = import.meta.env.VITE_REACT_APP_API_KEY;

I hope this helps..

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading