React 18 for begginers - GameHub - Environment Variables

Hi everyone. Hope you are doing well.

This is not really a post… more like a suggestion for curious people.

I did the course about React 18, and I’m super happy with it.
In the last chapter, we create a game discovery app, named GameHub. Mosh did an amazing job, explaining the best practices to apply.

Besides everything mentioned, by Mosh, I also would like to recommend not committing code, with API keys.

We just need to do some minor changes. First, lets define a .env.development file. In this file we can specify our api_key like this:

VITE_API_KEY="somekey"

Then we need to update our api-client.ts hook. The idea is the following. While running in development, we use the api_key specified above. In production, we need to specify an environment variable in Vercel.

This is the updated code for the api-client.ts:

import axios from "axios";

const apiKey = import.meta.env.DEV
  ? import.meta.env.VITE_API_KEY
  : process.env.API_KEY;

export default axios.create({
  baseURL: "https://api.rawg.io/api",
  params: {
    key: apiKey,
  },
});

During the build time, the compiler is not able to recognize the expression: process.env.API_KEY. We need to tell the compiler, what is the meaning of such expression. For that, we also need to update the vite.config.ts file:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  define: {
    "process.env.API_KEY": `"${process.env.API_KEY}"`,
  },
});

Hope I can help someone with this post. I created a repo, it the code here
@Mosh are we going to have a part 3 of the series?

Thanks,
Andre

1 Like

Yes should hide secrets in env variables, this is a good practice for security and maintainability by devops when values change like database password or API password

Hey! Thank you for your commenting. I was planning to cover this in part 3. Your solution is not really secure since the API key will ultimately be included in the bundle that is shipped to the client and will be visible in every network request in DevTools.

The right way to go about this is to build a backend and include the API key there so it’s invisible from clients. And of course, it should still be stored in an environment variable so it’s out of the source control.

I’m holding the production of part 3 for now because neither Next.js nor Remix are in a stable shape right now and I’m expecting some new and potentially breaking changes soon. I don’t want these changes to break my future course.

4 Likes

Hi, I did all of those steps as well as create an environment variable on Vercel. When I run the website on my local machine using “npm run dev” it works. whoever when I open the site on Vercel the key is undefined for some reason… am I doing something wrong? you need to give a specific name to the variable on Vercel?

Thank you!