LessonsHow to keep API keys out of your frontend

Mini lesson 15 of 30 · Accounts and access

Know which value must stay private

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.

The browser should use your feature without receiving the provider secret.

Purpose of this lesson

  • 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.
Explanation, worked example and practice

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.

Check your starting skills

These are useful skills, not locked course requirements. If you can already do them, start this lesson; otherwise open the linked preparation. The supplied starter files mean you do not need an existing personal website.

  1. How to publish your website from GitHub

    Connect a practice repository to hosting.

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.

Understand the idea

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

Start hereWorkshop files

Open or download the files below. When saving a project, keep the folder paths shown in the filenames.

Try it yourself

Which value must stay off the visitor’s page, and what evidence will you ask the assistant to inspect?

Show a worked solution

Illustrative privacy plan: “GEMINI_API_KEY is the private provider credential. LAB_TOKEN is a separate practice access code, not a replacement name for that key. The assistant will inspect the delivered public scripts and browser requests for accidental credential exposure.”

A private filename alone is not proof: a build could still copy its contents into public output. I will keep the real values out of screenshots and shared notes.

What a sound answer includes

  • Identifies the provider key as secret and the practice access code as a separate lab boundary.
  • Names public files and browser requests as the places to inspect for accidental key exposure.
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.

Step 1 · How to keep API keys out of your frontend

Start the supplied protected action

Let the assistant configure the existing server route.

Explanation, worked example and practice

Understand the idea

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.

Files for this step

Start hereWorkshop files

Open or download the files below. When saving a project, keep the folder paths shown in the filenames.

Try it yourself

Did the action run, and what private-setup or provider stage is still blocked?

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.

What a sound answer includes

  • 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.
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.

Step 2 · How to keep API keys out of your frontend

Check privacy and failure together

A useful reply does not excuse an exposed key.

Explanation, worked example and practice

Understand the idea

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.

Files for this step

Start hereWorkshop files

Open or download the files below. When saving a project, keep the folder paths shown in the filenames.

Try it yourself

What did the public-output check and the rejected attempt actually show?

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.

What a sound answer includes

  • States which public output/requests were inspected without reproducing the provider secret.
  • Records a rejected access attempt and an unavailable-configuration attempt as failures.
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.

Step 3 · How to keep API keys out of your frontend

Make one bounded change safely

Keep the same secret boundary when changing the feature.

Explanation, worked example and practice

Understand the idea

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.

Files for this step

Start hereWorkshop files

Open or download the files below. When saving a project, keep the folder paths shown in the filenames.

Try it yourself

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.

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.

What a sound answer includes

  • 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.
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.

Was this lesson useful?

Leave a like, or share it with someone who could use it.