Fetch API - Help a dumbass out.

I've stored it in a .env file called WEATHER_API_KEY in my App.vue I have 1 resource saying to save the API key to a variable called
process.env.WEATHER_API_KEY
process.env.WEATHER_API_KEY
and another saying
import.meta.env.VITE_WEATHER_API_KEY
import.meta.env.VITE_WEATHER_API_KEY
113 Replies
b1mind
b1mind4mo ago
your .env should look like
WEATHER_API_KEY=key
WEATHER_API_KEY=key
and you use it with the import you posted
CDL
CDLOP4mo ago
yeah, WEATHER_API_KEY=123456789
b1mind
b1mind4mo ago
https://vite.dev/guide/env-and-mode Oh no to use the meta you need to prefix both but only do that for public keys cause it WILL be sent to client
CDL
CDLOP4mo ago
so VITE_WEATHER_API_KEY
b1mind
b1mind4mo ago
yea
CDL
CDLOP4mo ago
const apiKey = import.meta.env.VITE_WEATHER_API_KEY;
const apiKey = import.meta.env.VITE_WEATHER_API_KEY;
that's what I had, haha, got something right at least Now... to write an async function to fetch... Following MDN it'd be something like...
const apiKey = import.meta.env.VITE_WEATHER_API_KEY;

async function getWeather() {
const url = `https://api.openweathermap.org/data/2.5/weather?q=London,uk&callback=test&appid=${apiKey}`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}

const json = await response.json();
console.log(json);
} catch (error) {
console.error(error.message);
}
}
const apiKey = import.meta.env.VITE_WEATHER_API_KEY;

async function getWeather() {
const url = `https://api.openweathermap.org/data/2.5/weather?q=London,uk&callback=test&appid=${apiKey}`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Response status: ${response.status}`);
}

const json = await response.json();
console.log(json);
} catch (error) {
console.error(error.message);
}
}
b1mind
b1mind4mo ago
yea but you need to return it idk how Vue does that either #depends on how you use it
ἔρως
ἔρως4mo ago
also, in one place you throw an exception but then you catch the important exception from response.json()? that doesn't make sense either you let all exceptions blubble up or you handle them all
CDL
CDLOP4mo ago
yeah I dunno this is confusing as shit for me, that's the literal example from the MDN docs minus the url being weather and not the MDN url example
ἔρως
ἔρως4mo ago
if you want to throw an exception, never catch other exceptions unless you want to repackage it somehow, but then it will make your life miserable when you start debugging that, you will tear your hairs out instead of that weird try{}catch, just do this:
const response = await fetch(url);

return response.ok ? await response.json() : false;
const response = await fetch(url);

return response.ok ? await response.json() : false;
but better indented
CDL
CDLOP4mo ago
every doc seems to have a different way of doing it haha..
fetch(`https://api.openweathermap.org/data/2.5/weather?q=London,uk&callback=test&appid=${apiKey}`)
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error('Network response was not ok');
}
})
.then((data) => console.log(data))
.catch((error) => console.error('There was a problem with the fetch operation:', error));
fetch(`https://api.openweathermap.org/data/2.5/weather?q=London,uk&callback=test&appid=${apiKey}`)
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error('Network response was not ok');
}
})
.then((data) => console.log(data))
.catch((error) => console.error('There was a problem with the fetch operation:', error));
ἔρως
ἔρως4mo ago
that works too but that's by using the promise directly, instead of the fancier await
CDL
CDLOP4mo ago
yeah the next example is async/await but it has the try catch again
ἔρως
ἔρως4mo ago
you can use the try catch but the way you were using was inconsistent
CDL
CDLOP4mo ago
async function fetchWeather() {
try {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=London,uk&callback=test&appid=${apiKey}`
);
if (response.ok) {
const data = await response.json();
console.log(data);
} else {
throw new Error('Failed to fetch data');
}
} catch (error) {
console.error('Error:', error);
}
}
fetchWeather();
async function fetchWeather() {
try {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=London,uk&callback=test&appid=${apiKey}`
);
if (response.ok) {
const data = await response.json();
console.log(data);
} else {
throw new Error('Failed to fetch data');
}
} catch (error) {
console.error('Error:', error);
}
}
fetchWeather();
ἔρως
ἔρως4mo ago
in my opinion, let the exceptions go unhandled
CDL
CDLOP4mo ago
yeah I feel like the exception/catch is making me more confused than I should be here
ἔρως
ἔρως4mo ago
it is
CDL
CDLOP4mo ago
I assume this is trying to get a response, and if it can, return the json, if it can't, it throws an error, but why is there a catch if it's alread doing an else: error if ok -> json, else -> error catch -> error
b1mind
b1mind4mo ago
try/catch is nice for serverside but idk how it benefits you on client but ya if you use try/catch don't throw new Error don't have an else
CDL
CDLOP4mo ago
Is there a simpler way to write this then? I'm pretty lost ngl. It also doesn't work haha, I just get "failed to fetch data at fetchWeather" and before that kept getting a 401
b1mind
b1mind4mo ago
if response.ok just return it unless you needed to do something else 🤷‍♂️
vince
vince4mo ago
Yea you're making it complicated, you have like 5 moving parts Vue, fetch, error handling, envs... Take it one step at a time 'How to create env variables in vue' 'How to call an api in vue' 'How to use fetch method in js' 'How to handle api calls in js' < and u dont even need this really like b1 said:
if (!response.ok) {
console.error('Failed to fetch weather');
return;
}

return data;
if (!response.ok) {
console.error('Failed to fetch weather');
return;
}

return data;
And stop calling yourself a dumbass, you're not. I think you get way more frustrated than you need to be and it makes it ten times harder You put all this pressure on yourself because you want to find a job but it just doesn't work like that, it's not sustainable. You'll burn out
b1mind
b1mind4mo ago
vince going deep xD I will say I agree with him though
vince
vince4mo ago
Honestly I'm just gonna say it how it is. It is not worth getting a web dev job in 2025 unless you're really passionate about it imo Think if you really wanna do this and if you do go all in, you can't half ass it But you need to be willing to do it because you like it, that's what will give you the ability (not motivation) to keep learning new things You either need to have passion or a lot of discipline, but if you don't have the passion why bother?
CDL
CDLOP4mo ago
I mean, 3 years and I can't even do a simple fetch API request 🤣 Getting a 401 error atm, I can't help but think Vue doesn't like this .env file
vince
vince4mo ago
401 is unauthorized so yea, it might be the env value. Console log it and see if it spits out the right valyr I didn't know about fetch until like last year and I've been learning since 2020 No one knows everything You fill in the knowledge gaps when you need to Right now you have a good use case to learn fetch so you're filling in the knowledge gap now And guess what when you need to make an api call in another project you'll know to use fetch, and it won't be as hard the second time
CDL
CDLOP4mo ago
seems to be 1 way for .env in VITE, and 1 way in VUE kinda confusing
b1mind
b1mind4mo ago
is it though? caues if you are using Vue then maybe you need to do the Vue way? 😄
vince
vince4mo ago
An env on the frontend is lowkey kind of useless anyway from a security perspective Just make it a variable worst case and use it
CDL
CDLOP4mo ago
I mean I'm just trying to hide my API key lmao
ἔρως
ἔρως4mo ago
wait wait wait are you trying to use an api key front the frontend?
b1mind
b1mind4mo ago
you can't that is why I said what I said
CDL
CDLOP4mo ago
Oh
vince
vince4mo ago
An env on the frontend is more for developer experience and reusability
b1mind
b1mind4mo ago
No description
vince
vince4mo ago
If you want a key hidden u use the backend It took me a while to learn that too
CDL
CDLOP4mo ago
oh, even if .env worked it looks like it'd still be visible through dev tools?
Jochem
Jochem4mo ago
I think there's services too that can hide it for you? But that's just using someone else's backend
vince
vince4mo ago
Yea
CDL
CDLOP4mo ago
I remember using postman yeeeears ago so doing it the backend way... I just need a server.js file and chuck my fetch request into there with the api key saved as a variable
vince
vince4mo ago
No don't do that man You already have enough complexity Do the frontend stuff first, get it working, and if you care enough make the backend after No one's looking to steal your api key and an employer is not going to ask and even if they do look at it you can explain what you know
b1mind
b1mind4mo ago
I mean if its a public api key it is what it is anyway worst case someone hits it and you get rate limited
CDL
CDLOP4mo ago
it's the openweather api key, i figured I'd want people to not be spamming it lol, I could be wrong. ehh anyway gotta sleep.. I got as far as "401 - invalid API key" which is annoying as I just made it an hour ago, unless it takes some time to "activate"
ἔρως
ἔρως4mo ago
that api key is not supposed to be public
vince
vince4mo ago
its not supposed to be but who is going to spam it lol and if it gets spammed its not like he has his card hooked up to it
ἔρως
ἔρως4mo ago
spam bots leeches
CDL
CDLOP4mo ago
ill look up how to hide it in the backend during downtiem at work tomorrow lol im sure it's not thaaat hard
ἔρως
ἔρως4mo ago
if it stays in the backend, then it is hidden that is all
b1mind
b1mind4mo ago
you have to have a backend for starters 🥲 NuxtJS time! >.>;;
CDL
CDLOP4mo ago
Nuxt do be quite easy to use, I’ve done it before (my workout app is Nuxt). So this is only needed if I want to hide the key, but there are public keys where I can just assign them to a variable and off I go. Alright. Is this a good use case for Nuxt? Or is something like this perfectly do-able frontend.. like what’s the deal here. Front-end for public keys but for private keys add a backend? I then have to make sure I’m not pushing this key to my GitHub repo eh.. not sure how I prevent that without breaking the repo?
vince
vince4mo ago
Gitignore but you're just adding way too much complexity imo
Ganesh
Ganesh4mo ago
What is the backend doing anyway. Previously you were using a public api key to query weather info. Which is fine if it's just a learning project imo.
CDL
CDLOP4mo ago
Nah it’s a private key, I don’t want people taking me monies
b1mind
b1mind4mo ago
I would use nuxtJS yes Or find another rest API or project
CDL
CDLOP4mo ago
This seems to be the general consensus..
No description
b1mind
b1mind4mo ago
Ummm ok..... Mate you need to learn not just get reference Idk where you got that 😂
CDL
CDLOP4mo ago
There’s learning and there’s repeatedly smashing my head against the wall in pure frustration :aspoggies:
b1mind
b1mind4mo ago
I mean that's kinda par for course
CDL
CDLOP4mo ago
A.yo.
vince
vince4mo ago
New Vue projects use Vite so you'd just use Vite's way of doing it which iirc is literally just making an env file
vince
vince4mo ago
No description
No description
Ganesh
Ganesh4mo ago
That would embed variables in the frontend code right?
vince
vince4mo ago
No description
No description
Ganesh
Ganesh4mo ago
Ok so it is exposed to frontend when prefixed with VITE
vince
vince4mo ago
Ya If you ever see something like this don't even bother Unformatted code I mean lol If they can't even format the code or it's a website that doesn't format it for you it's probably not worth spending your time looking at the answers unless you have a really niche issue
b1mind
b1mind4mo ago
How is he supposed to use it 🥲 If he does that it's still only available to the backend/build tool Best to understand this stuff too don't just listen to us 😂 I feel like you look for answers more than you discover them
Ganesh
Ganesh4mo ago
Well reading nuxt docs instead of messing with vite since that's what the backend will run
CDL
CDLOP4mo ago
Tryyyyyying to understand it but it’s not straight forward and every bloody framework/build tool has its own way of doing it
Ganesh
Ganesh4mo ago
Dunno if nuxt uses vite under the hood
b1mind
b1mind4mo ago
Ofc it does
Ganesh
Ganesh4mo ago
Ofc
b1mind
b1mind4mo ago
Ofc! You know who made it right?
vince
vince4mo ago
wym?
b1mind
b1mind4mo ago
What do you mean You are the one that told him to just do that
vince
vince4mo ago
How is he supposed to use the env? I don't understand what you were saying there lol
b1mind
b1mind4mo ago
That's where we started man
vince
vince4mo ago
Vue is built via Vite so just use the Vite way of making env variables In your vue files
b1mind
b1mind4mo ago
And if it's not a public key that's all just sent to the client
vince
vince4mo ago
I know I'm recommending him to just not even bother w the backend
b1mind
b1mind4mo ago
Then he needs a different rest API that uses public not private keys
vince
vince4mo ago
I agree, I was sending what I sent because of the message he sent with the random forum answer lol I was trying to show him how to google it 😅
b1mind
b1mind4mo ago
Yea idk what that shit was Chatgpt response 😂
vince
vince4mo ago
fr
b1mind
b1mind4mo ago
Learn how what you will use does it.. why get confused with others. NuxtJS is Vue official fullstack framework. "meta framework" 😭
Ganesh
Ganesh4mo ago
I in fact did not know this
CDL
CDLOP4mo ago
My brain = :poggies: (seriously who makes these emojis) .env is pointless if I have to VITE it which reveals the key. Whole point here is to hide the key as it's a private one (starts to charge based on amount of usage).. meaning the only way is a backend proxy (or nuxt) So I now have my API showing when I go to localhost:3000/api/weather .. There were a few issues in my code. 1) I didn't have dotenv imported into my server.js
import dotenv from 'dotenv';
dotenv.config();
import dotenv from 'dotenv';
dotenv.config();
2) I was opening the server at localhost:3000 and not localhost:3000/api/weather oh and I didn't have the localhost configured in my vite.config.js either.
CDL
CDLOP4mo ago
No description
b1mind
b1mind4mo ago
Do you even need dotenv? xD
CDL
CDLOP4mo ago
stupid question - I had to have 2 terminals open in vscode, 1 to run "node server.js" and 1 for "pnpm run dev", is that normal?
b1mind
b1mind4mo ago
sure You could run them in tandom too though concurrently I guess is proper wordering
{
"scripts": {
"client": "npm start --prefix client",
"server": "nodemon index.js",
"dev": "concurrently \"npm run client\" \"npm run server\" "
}
}
{
"scripts": {
"client": "npm start --prefix client",
"server": "nodemon index.js",
"dev": "concurrently \"npm run client\" \"npm run server\" "
}
}
something like this
CDL
CDLOP4mo ago
oh interesting
Ganesh
Ganesh4mo ago
Nuxt uses dotenv under the hood and automatically reads from env file. If you're using something like express. Yeah gotta install dotenv Also this script is just an example I know but nodemon isn't needed in current node versions from v20 iirc. They have --watch flag now Also this import can be shortened by using side effect imports. The npm page documention prefers this for ES modules import "dotenv/config" And the way you used it can cause problems with other import statements
CDL
CDLOP4mo ago
Appreciate it, thanks 👍 Hmmm... so, is my api key actaully hidden once I host this on github, or is there still a way to access it? what I've done: - .env file - server.js -> access api key from here (key digits aren't mentioned, it's a const apiKey = process.env.WEATHER_API_KEY; to grab the key from the .env file - .env file is then added to .gitignore
ἔρως
ἔρως4mo ago
i think you have to store the key in the project's secrets
b1mind
b1mind4mo ago
Github hosting has 0 backend support 🥲 its for static stuffs
CDL
CDLOP4mo ago
Ah so cloudflare, I know cloudflare has secrets
ἔρως
ἔρως4mo ago
oh, right, he needs a backend 🤦‍♂️ cloudflare is static only too
b1mind
b1mind4mo ago
cloudflare can do serverless functions though?
CDL
CDLOP4mo ago
Stupid question but the repo IS hiding the key right? 🤣 (please don’t laughing too much)
b1mind
b1mind4mo ago
yes if you ignored the .env you can just look yourself dork
CDL
CDLOP4mo ago
Yeah I know I couldn’t see it anywhere but I didn’t know if I was missing something I’ve spent all day learning DSA, my brain’s fried ok 😢
b1mind
b1mind4mo ago
learning DSA? in the age of LLMs? <,<;;
CDL
CDLOP4mo ago
LLM’s don’t help me brain understand this shit, it just does it for me 🤣
b1mind
b1mind4mo ago
Like one the few things its good at 🤣 I mean DSA for web dev is wasted space to start with You will like never use those skills 🥲
CDL
CDLOP4mo ago
I’m not doing all of DSA
ἔρως
ἔρως4mo ago
dsa? data storage algorithms?
b1mind
b1mind4mo ago
sorting
ἔρως
ἔρως4mo ago
oh
b1mind
b1mind4mo ago
reverse a binary tree *meme
CDL
CDLOP4mo ago
Nah not that I LLM’d this shit and said “what’s gonna help me stop sucking in web dev” and it spit out a few from a udemy course I have on JavaScript algos 💀 (big o notation, recursion, “problem solving approach/patterns”, searching/sorting algos Nothing heavy Anyway. Cloudflare secrets/serverless, lemme look
b1mind
b1mind4mo ago
I love how you will ask LLM existential questions like that 🤣 we are so cooked as humans
CDL
CDLOP4mo ago
My brain works in mysterious ways my friend My entire study life has been just bashing out code, I’m a coder, not a programmer. I want to be a programmer 🥲

Did you find this page helpful?