📎 Webclip
Protecting your API keys with Next JS
The page explains that API keys placed in frontend code can still appear in the network tab. It recommends using a server-side proxy instead, and presents Next.js API Routes as a ready-to-use Node.js environment for that purpose.
Reading notes#
- It frames the problem through Max, who thinks an
.envfile keeps API keys safe, but the keys are still visible in the network tab. - It says there is no good way to protect keys in the frontend, so the request should go through a backend proxy because backend code is not exposed to the browser.
- It describes Next.js API Routes as an integrated server-side option that can serve API endpoints.
- It shows a basic setup with
npx create-next-app next-api-keyoryarn create next-app next-api-key, thencd next-api-key. - It introduces
.env.localas a file whose variables are only available in Next.js’s Node.js environment, not in the browser. - It shows an example
pages/api/hello.jsendpoint that returns JSON from the server side. - It shows the client calling
/api/hellofrom the browser. - It places
SECRET_KEY=someSecretKeyThatNoOneShouldSeein.env.localand usesprocess.env.SECRET_KEYinsidepages/api/hello.js. - It notes that
fetchis not available in Node, so a library likeaxiosornode-fetchis needed for server-side requests. - It ends by saying the key is no longer visible in the network tab when the request goes through the API route.
