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.

Start the interactive lessonRead the lesson below

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.

Workshop files

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

Start hereWorkshop files

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.

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

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.

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

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.

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

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.

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.

Continue learning

Explore the other lessons