
Mini lesson · English
How to keep API keys out of your frontend
Use a supplied server-backed example to keep a provider key out of the visitor’s browser and verify allowed and rejected requests.
Who is this for?
People connecting a website to an AI or other privileged service. A coding assistant can wire the ready project; you need to understand where your secret may be used, not write server code.
Before you start
Your own Google AI Studio API access and a separate Netlify-function practice project. Use a coding assistant with the complete workshop and private environment setup. Confirm the model and account usage limits, including any possible charges, before making requests. The lab uses a separate owner-held practice code; it is not a ready public AI service.
Estimated time: 20–32 min
Estimates for the supplied starter files with prerequisite accounts and tools ready. Setup, deployment queues and delivery/DNS waits take additional time. Provider/account setup may take longer. Usage is subject to your account's current terms and quota.
What you will learn
- Put the provider secret only in the private server environment.
- Run the supplied action without exposing the key to visitors.
- Check successful and rejected access attempts.
Step 1
Know which value must stay private
The browser should use your feature without receiving the provider secret.
Open the supplied project with your assistant. Identify the provider key as a private account value and the separate practice code as the owner’s access control for this small lab.
A file being named .env is not enough if a build copies its value into public scripts. Ask the assistant to inspect the actual visitor-facing files.
A concrete example
A hidden form field still belongs to the browser and cannot conceal a provider key.
Open this ready API-key workshop and guide its run-locally.txt setup. Keep the provider key and model choice on the server and use a separate practice access code. Do not put secrets in public files or ask me to paste them into shared messages. Help inspect what the browser receives and test both allowed and rejected requests. Explain the observable evidence instead of requiring me to implement the endpoint.Files for this step
Open or download the files below. When saving a project, keep the folder paths shown in the filenames.
How it works (optional)
Keep privileged API keys out of browser code
The visitor's browser can inspect every file you send it.
A provider secret can authorize spending or privileged operations. Putting it in public JavaScript, a hidden field or an environment variable substituted during a frontend build still sends it to the browser.
The worked example asks Gemini one fixed educational question through your server function. The browser receives the answer; the provider key stays in the server environment. Not every key is secret: Supabase publishable keys are designed for browser use with access policies, while its secret keys are not.
Worked example
Open insecure-example.txt. The fake value is visible because it is in delivered code. Minifying the same line would make it less readable, but would not change who receives it.
Extra implementation exercise
A key is stored in .env, then inserted into the public JavaScript bundle during build. Is it private from visitors?
Show a worked solution
No. Its original file location does not matter after it is inserted into a public bundle. Move the privileged operation to a server function and keep the value there.
- Follows the key into the delivered bundle.
- Distinguishes server environment from frontend substitution.
Common mistake
Treating every variable named SECRET as private regardless of where it is shipped.
Step 2
Start the supplied protected action
Let the assistant configure the existing server route.
Follow run-locally.txt and server-env.example.txt with your assistant. Confirm the intended account/model and usage terms, set the provider key privately on the server and generate a separate practice code. Run the complete project and open the local app URL. These setup checks are required; writing the function code is optional.
The browser should talk to your server feature while the server calls the provider privately. If setup, access or quota fails, report that stage rather than inventing a reply.
A concrete example
The form’s practice code is not the Google provider key.
Gemini generateContent API · Gemini API keys · Gemini: current model IDs and capabilities · Node.js: supported release status
Try it yourself
Did the action run, and what private-setup or provider stage is still blocked?
Discuss your answer with the lesson tutor
Show a worked solution
Illustrative readiness result: “The complete project opened at the local proxy URL. With the practice access code, its server action returned a brief explanation of a website server. Provider credentials and model choice stayed in the private environment.”
A blocked example is “The app runs, but the provider reports unavailable quota; no successful reply was observed.” Check your account’s allowed models, limits and possible charges before repeating requests; this lesson does not promise free or unlimited calls.
- Records the real local app address and one allowed action or an exact configuration/provider blocker.
- Keeps the provider credential/model on the server and checks account usage terms before calling it.
Files for this step
Open or download the files below. When saving a project, keep the folder paths shown in the filenames.
How it works (optional)
Put the provider call behind your own endpoint
Configure the server, then send only the small request the feature needs.
Read netlify/functions/mini-explain.mjs, deploy the separate project and set GEMINI_API_KEY, GEMINI_MODEL and LAB_TOKEN on its server. Choose a supported text model in your account rather than copying an old model name from a tutorial.
Enter the independent practice code into the form. The browser calls /.netlify/functions/mini-explain; that function calls Google's fixed HTTPS endpoint with x-goog-api-key. The code is an owner-only lab restriction, not the Gemini credential and not a full public quota system.
GEMINI_MODEL is the exact model ID available to your own API account, not a display label copied from a screenshot. generate is a helper in the same server function file. Neither the provider key nor that helper belongs in public/. A valid request may still fail when the provider has no quota or is unavailable.
For the complete local sequence, open run-locally.txt: prepare the private root environment, link only the practice project and start the Netlify function proxy. server-env.example.txt lists variable names without real secrets. Opening only the HTML cannot run the server.
Use the current model guide below, or run list-text-models.mjs from the private workshop root with your own environment. It lists account-visible generateContent candidates without printing the key. Choose a supported text model, check its terms/quota, then copy its exact API ID into the server GEMINI_MODEL setting.
Before the first function request, run the model-list helper and select a current text model that supports the generateContent request fields used here, including systemInstruction. The list identifies candidates, not quota or every model capability. The entire netlify/functions/mini-explain.mjs file runs on the server; public/app.js is delivered to every visitor. Also check the hosting plan’s function timeout: the provider’s 20-second deadline cannot extend a shorter host limit.
Worked example
The provider prompt is fixed on the server, so a caller cannot turn this route into arbitrary large prompts. The function also bounds output and waits at most 20 seconds for its provider request.
Gemini generateContent API · Gemini API keys · Gemini: current model IDs and capabilities · Node.js: supported release status
Extra implementation exercise
Which two requests should you see, and which one should be absent from browser Network tools?
Show a worked solution
The browser shows its call to your function and the returned answer. The server makes the provider request; its credential-bearing Google call should not appear as a browser request.
- Sees the browser request to the own-site function.
- Keeps the authenticated Google request on the server.
Common mistake
Copying the server helper into public/ to fix a path error.
Step 3
Check privacy and failure together
A useful reply does not excuse an exposed key.
Ask the assistant to help inspect delivered public files and browser requests for the provider secret without displaying it in shared logs. Try a wrong practice code and a missing configuration case in the disposable project.
The actual key must not appear in browser files/requests. Rejected or unavailable requests must remain failures, with a usable retry route.
A concrete example
A convincing answer plus a key exposed in app.js is still an unfinished task.
Try it yourself
What did the public-output check and the rejected attempt actually show?
Discuss your answer with the lesson tutor
Show a worked solution
Illustrative privacy/error record: “The assistant inspected the public output and browser request to my own server; the provider key was absent. A wrong practice code was rejected. With private provider configuration removed in the disposable setup, the action failed rather than displaying a fabricated explanation.”
This records the inspected boundary, not a complete security audit. If a key is found in public output, stop sharing that build and replace the exposed credential through the provider before using it again.
- States which public output/requests were inspected without reproducing the provider secret.
- Records a rejected access attempt and an unavailable-configuration attempt as failures.
Files for this step
Open or download the files below. When saving a project, keep the folder paths shown in the filenames.
How it works (optional)
Verify both the boundary and the answer
A successful reply alone does not prove the key stayed private.
Search the deployed public HTML and scripts for the actual provider key without pasting it into screenshots or shared logs. Inspect browser requests: the practice code may be visible to its owner, but the Gemini key must not be.
Test a wrong practice code and missing provider configuration in the disposable project. A failure must remain a failure. Provider status 429 can indicate quota/rate limits; 401 or 403 can indicate access/configuration issues. Do not turn all of them into a fabricated AI answer.
Worked example
A correct practice code with valid provider settings should return a real answer. The same endpoint with a wrong code should reject before any provider request.
Extra implementation exercise
The answer works, but the provider key also appears in public/app.js. Is the task complete?
Show a worked solution
No. Remove the key from public files, rotate it because it was exposed, update the server setting and check the new deployment and repository history for remaining exposure.
- Rejects successful output as sufficient evidence.
- Removes the leak and rotates the exposed key.
Common mistake
Hiding a leaked value in the UI while leaving it in a downloadable script.
Step 4
Make one bounded change safely
Keep the same secret boundary when changing the feature.
Ask the assistant to adapt the supplied fixed operation to explain DNS briefly. Preserve server-side model/key settings and the owner-only practice boundary.
Test the intended response and an invalid access code again. Before public use, decide on real authentication, durable usage controls and monitoring for your provider budget.
A concrete example
Changing the answer topic should not move private account values into the page.
Try it yourself
Start with these materials
The starter files and test content are supplied. A live verification still requires your own permitted provider account, inbox or domain as listed under prerequisites. Local inspection is possible without them; record the live step as not tested until you actually perform it.
Provide the changed action and the privacy/valid/invalid checks you actually ran.
What to produce A redacted key-boundary and valid/invalid request record for the supplied action.
Discuss your answer with the lesson tutor
Show a worked solution
Illustrative change record: “The fixed operation now explains DNS in two sentences. A permitted practice call returned that topic; a wrong practice code was rejected; the public-output check still found no provider key.”
“Before opening this to strangers, I still need real authentication, durable usage limits and provider-budget monitoring.” The shared practice code is a small lab boundary, not evidence of a complete public service.
- Changes the fixed response topic to DNS while preserving server-only key/model settings.
- Retests the allowed and rejected calls and names remaining public-use cost/access controls.
Files for this step
Open or download the files below. When saving a project, keep the folder paths shown in the filenames.
How it works (optional)
Your assignment: move a second fixed operation
Repeat the boundary deliberately instead of widening it accidentally.
Change the server's fixed prompt to explain DNS in two sentences. Keep credentials, model choice and the output bound on the server; keep the browser unaware of the provider key.
Record the result with a valid and invalid practice code. Explain what you would add before public access: authenticated users or another meaningful access boundary, durable usage limits, and monitoring against the provider budget.
Worked example
Changing a fixed prompt proves you understand where provider behaviour is controlled. Accepting arbitrary models, endpoints or output limits from the browser would undo that control.
The complete reference walkthrough is available in reference/assignment-walkthrough.txt. Compare its steps with your own result; fill the test record from observations in your own project.
Extra implementation exercise
Produce the DNS version and a short boundary test record.
Show a worked solution
In the server-only mini-explain function, replace the fixed question about a website server with 'Explain DNS in two sentences for a beginner.' Keep the key/model in server environment variables; the full reference function shows the exact edit.
Inspect browser-delivered scripts and Network requests. The browser sends its request to your own function; it must not send GEMINI_API_KEY to Google itself. The owner-entered lab code is separate from the provider key.
Try a wrong practice code: expect rejection before any provider call. A provider quota/network failure must remain an honest failure, not a canned successful answer. If a real secret was exposed, remove it and rotate it; ignoring the file afterward does not revoke exposure.
- No provider secret is delivered to the browser.
- Wrong access is rejected and an honest provider failure is visible.
Common mistake
Calling the restricted workshop a production-ready public AI service.
Was this lesson useful?
Leave a like, or share it with someone who could use it.
Continue learning
- How to build your first personal website
- How to publish your website from GitHub
- How to connect a custom domain to your website
- How to set up email on your own domain
- How to make your website usable on phones
- How to make website images load faster
- How to get website feedback in your inbox
- How to add email subscriptions to your website
- How to send automated emails from your website
- How to save form submissions in a database
- How to let people sign in to your website
- How to keep a page private
- How to let users edit their profile information
- How to let users upload images
- How to show data from an external API on your website
- How to add an AI chatbot to your website
- How to make a chatbot answer from your own content
- How to add a blog to your website
- How to add search to your website
- How to add another language to your website
- How to help Google find your website
- How to fix your website preview when sharing a link
- How to measure visits and useful actions on your website
- How to let visitors book an appointment
- How to accept a payment on your website
- How to preview website changes before publishing
- How to undo a broken website deployment
- How to back up and restore your website data
- How to find and fix errors on your live website