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}

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..

Leave a Reply