Keep the Key Off the Page

Your partner now supports a long practice session at a steady cost, but only in the terminal. Club members will chat on the club’s page, so the reply has to get there.

In this lesson, you’ll see what each provider does when the page’s script calls it, where the key ends up, and what to build instead. Start with the call most developers would try first.

Call the Provider From the Page

The shortest route seems to be moving the fetch() call from model/ into the page’s script, key and all. Before a page’s script can read an answer from another site, though, the browser checks whether that site allows it. This check is called CORS, short for cross-origin resource sharing.

A small test page shows how each provider answers. Its Send button sends Amara’s first message with stream: true and logs the response’s status and Content-Type. Read the runs rather than pasting your key into a page. Open the version for your provider:

The page sends the streamed request from the start of this course, with the key in the script:

Language: HTML Filename: key-in-page.html
<!doctype html>
<title>Practice partner</title>
<button>Send</button>
<script>
  const API_KEY = "paste-your-key-here";
  const button = document.querySelector("button");

  button.addEventListener("click", async () => {
    const response = await fetch(
      "https://api.openai.com/v1/responses",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${API_KEY}`,
        },
        body: JSON.stringify({
          model: "gpt-6.1-terra",
          input: "Hola, quiero una café con leche.",
          max_output_tokens: 400,
          stream: true,
        }),
      },
    );
    console.log(
      response.status,
      response.headers.get("Content-Type"),
    );
  });
</script>

With a real key, clicking Send logged this in the Console:

Language: Program Output
200 text/event-stream

OpenAI lets any page read its answers, so the page got the same stream your terminal scripts read. The key works from every visitor’s browser.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.