I've been trying to create a YouTube clone with RapidAPI and all is working except the enviroment variable I want to use for API key. I'm getting back 403 forbidden every time I try to fetch data with import.meta.env.VITE_API_KEY
(in Vite app) as apiKey
value, even though when I log it, it shows valid key.
I've tried to modify vite.config.js
with adding envDir: "./", define: { "process.env": process.env,}
in defineConfig, and even tried to recreate the app with Create React App and use or process.env.REACT_APP_API_KEY
, with same result. Only when I copy/paste the key directly in header, it works with no problem.
Here is my code:
.env file:
VITE_RAPID_API_KEY=xxxxxxxxxxxxxxxxxx
fetchFromApi.js:
import axios from "axios";
const BASE_URL = "https://youtube-v31.p.rapidapi.com";
const apiKey = import.meta.env.VITE_RAPID_API_KEY;
export const fetchFromApi = async (url, searchTerm, setData) => {
const options = {
method: "GET",
url: `${BASE_URL}/${url}`,
params:{
q: searchTerm,
part: "snippet,id",
maxResults: "50",
},
headers: {
"X-RapidAPI-Key": apiKey,
"X-RapidAPI-Host": "youtube-v31.p.rapidapi.com",
},
};
axios
.request(options)
.then(function (response) {
setData(response.data.items)
})
.catch(function (error) {
console.error(error);
});
};
I call it in my components like this: fetchFromApi('search', selectedCategory, setVideos)