CodingNic

Connect the Movie Data

Keep the TMDB Key on the Server

Connect the Movie Data 8 min read

Keep the TMDB Key on the Server

Keep the TMDB Key on the Server

The app needs an API key, but the key should not be embedded in browser code. In this step you will add one small helper that reads the environment variable only when the server-side TMDB client needs it.

Step 1 — Read the environment variable

In lib/tmdb.ts, add apiKey below the constants.

typescript
function apiKey(): string {
  const key = process.env.TMDB_API_KEY;

Check for a missing value immediately rather than letting the request fail later with a vague error.

typescript
if (!key) {
  throw new Error(
    "TMDB_API_KEY is not set. Add it to .env.local — see .env.local.example."
  );
}

Return the key from the helper.

Step 2 — Create the local environment file

Copy .env.local.example to .env.local, then put your own TMDB v3 API key in the variable named TMDB_API_KEY.

Do not add the key to any component file. The page will call functions from lib/tmdb.ts, and those functions will access the environment value on the server.

Checkpoint

With a valid key configured, the server can read TMDB_API_KEY. With the key removed, the helper produces the explicit setup error instead of attempting an unauthenticated request.