How to access .env variables from client side JS

Hi, FCC folks. I have a small web app that I’m working on to be used as a helper to a word game that’s in the New York Times every Sunday. Very simple. Just checks to see if your word meets the criteria of the game, then adds it to a list and updates your score. I would like to add a function that allows you to display the definition of a word you’ve played by clicking on it. The app, without this function, is all front end, but the Webster’s Dictionary API that I’m trying to use requires a key. I think this means I must have a server side as well, in order to have a .env file to hide my key in. I got that up and running in a Glitch project, but now when I try to access process.env.API_KEY from my client side JS, that’s still a no-go, because I can only access that from my server. So now I’m not sure how to go about getting access to my api key. Maybe I’ve structured this all wrong for what I’m trying to do, since I thought the whole thing could be done in-browser?
My project can be found here: https://glitch.com/edit/#!/nyt-spelling-bee-helper
The piece I’m trying to add to the project is in client.js, starting at line 122, (commented out so the app will still work).
Any advice on how to proceed would be greatly appreciated!

1 Like

But you do have server.js, so you’re pretty much half way there :slight_smile:
Just add one simple end point on your server, something like:

app.get('/api/words', (req, res) => {
  const word = req.query.word.toLowerCase();
  // fetch word with library of your choice using secret API from .env
  .then(data => res.send(data));
});
1 Like

I think the question is answered above but I want to point out something here as I believe its pretty critical.

Don’t send secrets to the client, unless they are “public” in the sense you could hand them out to hackers on a silver platter and not worry about it.

Stuff like datebase access information, hashes used for encryption, important environment variables, passwords, and other “server-side secrets” should never be given to the client, as anyone can inspect the network/js/html/code to see those secrets.

Stuff like API tokens are in a vague limbo, as there are scenarios where its totally find to put them/give them to client side code, as they usually are limited, or check the domain the request is coming from. An example of this would be [google’s analytics](http://import {MatListModule} from ‘@angular/material/list’:wink: scripts, which are there to keep track of page views 100% on the client-side, as such their “api-keys” are fine to expose publicly.

A lot of this can be also applied to committing secrets into source code, the last thing you want to someone to look into your github, and get your database access keys and delete all your data (!).

Good luck, stay secure :smiley:

1 Like