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