TMDB API JavaScript tutorial: movie cards with Node.js fetch
A TMDB API JavaScript client needs no npm package, because Node 20 ships fetch. This tutorial builds a script that takes movie ids and prints title, year, director, top cast and every known rating, at 1 request per id. It uses the TMDB v3 JSON shape against https://api.amodb.dev/3 and takes 15 minutes.
The TMDB API works from JavaScript with the built-in fetch in Node 20 or newer, so the script needs no npm package. It uses the TMDB v3 JSON shape and runs against amodb at https:/, so only the base URL and the key differ from TMDB. Each movie id costs 1 request, because credits and ratings arrive through append_to_response.
What do you need to follow this tutorial?
You need Node.js 20 or newer, an amodb key and about 15 minutes, and nothing else.
| You need | Details |
|---|---|
| Node.js | 20 or newer, which ships fetch, URL and AbortSignal.timeout |
| Packages | None, zero npm dependencies |
| API key | An amodb key: 32 lowercase hex characters, the same shape as a TMDB v3 key. Plans start at $5.19 a month and there is no free tier. |
| Base URL | https:/ (TMDB uses https:/) |
| Time | About 15 minutes |
| Result | A script named cards.mjs that prints title, year, runtime, director, top 3 cast and every known rating |
Which calls does the script make, and what do they cost?
The script sends 1 call per movie id, and each call counts as 1 request toward the 20, 40 or 120 requests per minute of your key.
| Call | Path | Edge cache | Cost in requests |
|---|---|---|---|
| Details with credits and ratings | GET / | 6 hours | 1 per id |
| Same id again, inside 6 hours | Read from .amodb-cache.json | Not applicable | 0 |
| Details, credits and ratings as separate calls | Three paths per id | 6 hours each | 3 per id |
On the 20 requests per minute plan that is about 20 fresh ids a minute, and the 40 and 120 plans give about 40 and 120. A reply served from the edge cache still counts as a request, but a hit in the script's own file cache costs 0.
Step 1: Get an API key
Buy a plan on amodb pricing with your email, sign in with the 6 digit code amodb then emails you, copy the first key, which is shown once, and put it in the AMODB_KEY environment variable.
Plans differ in requests per minute: 20, 40 or 120. Every plan has every TMDB v3 compatible endpoint, the OMDb compatible endpoint, images, 14 languages and the extensions, and Pro+ also has the all in one endpoint GET /, which this script does not call. You pay by card, Apple Pay or Google Pay for 1 to 24 months with no automatic renewal, or monthly through Patreon, which renews on Patreon until you cancel there.
The key is 32 lowercase hex characters, the same shape as a TMDB API key, and the authentication page lists the ways to send it. Put the key in the environment:
The script reads process.env.AMODB_KEY, so the key never lands in the source or in version control.
export AMODB_KEY="YOUR_API_KEY"Step 2: Create the project
Make a folder and an empty cards.mjs file, because there is nothing to install.
The version must print v20 or higher. The .mjs extension turns on ES modules without a package.json.
mkdir movie-cards && cd movie-cards
node --versionStep 3: Send the first request
Call GET / with the key in an Authorization header and a timeout, then check the status before you parse the body.
Movie 550 is Fight Club, and the snippet prints its HTTP status and title.
const res = await fetch('https://api.amodb.dev/3/movie/550?language=en-US', {
headers: { Authorization: `Bearer ${process.env.AMODB_KEY}` },
signal: AbortSignal.timeout(10_000),
});
console.log(res.status, (await res.json()).title);Step 4: Add credits and ratings
Append credits,ratings to the movie call so that one request returns the details, the cast and crew lists and the five rating sources.
Each source sits under its own key inside ratings. That is one request per movie instead of three, and the whole call counts once against your 20, 40 or 120 requests per minute. The director is the crew member whose job is Director. Fields are described on the credits API and movie ratings API pages.
In ratings, each source is { value, votes } or null. IMDb, Kinopoisk and TMDB values are out of 10, and Metacritic and Rotten Tomatoes values are out of 100. The card formatter below skips nulls and joins the rest:
const scores = Object.entries(movie.ratings ?? {})
.filter(([, entry]) => entry !== null)
.map(([source, entry]) => `${source} ${entry.value}`)
.join(', ');Step 5: Handle errors and rate limits
Map each failure status to one decision: stop the run, skip the id, or wait and retry.
| Status | Decision |
|---|---|
| 401 | Stop the whole run. A wrong or suspended key fails every id. |
| 404 | Report the id and continue with the next one. |
| 429 | Wait Retry-After seconds (cap 30) and retry, up to two retries. |
| 504 | Retry on the same schedule, then report. |
| Timeout or no network | Wait one second times the attempt number, then report on the third failure. |
The X-RateLimit-Remaining header shows how many calls are left in the current 60 second window. Log it if you want to slow down before a 429 happens. See rate limits for the window rules and error codes for the full list.
Step 6: Add a small cache
Keep a Map of { expires, data } entries that is loaded from .amodb-cache.json at the start and written back at the end.
Details are cached at the edge for 6 hours, so asking again inside that time returns the same data. Cache on your side to skip the call altogether. A second run over the same ids makes no requests.
Step 7: The complete program
Save the complete program as cards.mjs and run it with node cards.mjs 550 603 27205.
Run it twice. The first run sends one request per id, plus a retry if a 429 comes back, and writes .amodb-cache.json. The second run prints the same cards and sends nothing. Delete the file to force a refresh. An id that does not exist prints 404: The resource you requested could not be found. and sets the exit code to 1, which helps when the script runs inside a scheduled job.
The loop is sequential on purpose. Running all ids at once would burn through a per-minute budget in one burst and trigger the 429 path for most of them. If you need speed, process ids in groups of five and keep the retry logic in request().
import { readFile, writeFile } from 'node:fs/promises';
const BASE = 'https://api.amodb.dev/3';
const KEY = process.env.AMODB_KEY;
const CACHE_FILE = '.amodb-cache.json';
const DETAILS_TTL_MS = 6 * 60 * 60 * 1000;
if (!KEY) {
console.error('Set AMODB_KEY first.');
process.exit(1);
}
class ApiError extends Error {
constructor(status, message) {
super(`${status}: ${message}`);
this.status = status;
}
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function request(path, params = {}) {
const url = new URL(BASE + path);
for (const [name, value] of Object.entries(params)) url.searchParams.set(name, value);
for (let attempt = 1; attempt <= 3; attempt++) {
let res;
try {
res = await fetch(url, {
headers: { Authorization: `Bearer ${KEY}` },
signal: AbortSignal.timeout(10_000),
});
} catch (err) {
if (attempt === 3) throw new Error(`network error: ${err.message}`);
await sleep(1000 * attempt);
continue;
}
if (res.status === 401) {
throw new ApiError(401, 'the key is invalid or suspended. Check AMODB_KEY.');
}
if ((res.status === 429 || res.status === 504) && attempt < 3) {
const seconds = Math.min(Number(res.headers.get('Retry-After')) || 1, 30);
await sleep(seconds * 1000);
continue;
}
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new ApiError(res.status, body.status_message ?? res.statusText);
}
return res.json();
}
}
async function loadCache() {
try {
return new Map(Object.entries(JSON.parse(await readFile(CACHE_FILE, 'utf8'))));
} catch {
return new Map();
}
}
async function cachedGet(cache, path, params, ttlMs) {
const key = `${path}?${new URLSearchParams(params)}`;
const hit = cache.get(key);
if (hit && hit.expires > Date.now()) return hit.data;
const data = await request(path, params);
cache.set(key, { expires: Date.now() + ttlMs, data });
return data;
}
function formatCard(movie) {
const year = (movie.release_date ?? '').slice(0, 4) || 'n/a';
const director = movie.credits.crew.find((p) => p.job === 'Director')?.name ?? 'unknown';
const cast = movie.credits.cast.slice(0, 3).map((p) => p.name).join(', ');
const scores = Object.entries(movie.ratings ?? {})
.filter(([, entry]) => entry !== null)
.map(([source, entry]) => `${source} ${entry.value}`)
.join(', ');
return [
`${movie.title} (${year}), ${movie.runtime ?? '?'} min, directed by ${director}`,
` Cast: ${cast || 'none listed'}`,
` Ratings: ${scores || 'none known'}`,
].join('\n');
}
const ids = process.argv.slice(2);
if (ids.length === 0) {
console.error('Usage: node cards.mjs 550 603 27205');
process.exit(1);
}
const cache = await loadCache();
let failed = false;
for (const id of ids) {
try {
const params = { language: 'en-US', append_to_response: 'credits,ratings' };
console.log(formatCard(await cachedGet(cache, `/movie/${id}`, params, DETAILS_TTL_MS)));
} catch (err) {
console.error(`id ${id}: ${err.message}`);
failed = true;
if (err.status === 401) break;
}
}
await writeFile(CACHE_FILE, JSON.stringify(Object.fromEntries(cache)));
process.exitCode = failed ? 1 : 0;How do I use this code in React or Next.js?
Keep the key on the server and send React only the fields it renders.
Move request() and formatCard() from Step 7 into a server route, such as a Next.js route handler or an Express handler, and return a small JSON object with title, year, cast and scores. The browser then loads posters straight from https:/, which needs no key. For a full page on top of the same API, see the Next.js movie app tutorial.
How do I switch this code between TMDB and amodb?
Change BASE and the key, and read the score fields that your service returns.
| Setting | TMDB | amodb |
|---|---|---|
BASE constant | https:/ | https:/ |
| Key | Your TMDB key | Your amodb key, sent as Authorization: Bearer or ?api_key= |
| Scores | vote_average, vote_count and imdb_id | ratings with IMDb, Kinopoisk, Metacritic, Rotten Tomatoes and TMDB, each can be null |
| Rate limit | About 40 requests per second per IP, and TMDB says it could change | 20, 40 or 120 requests per minute per account, no daily cap |
TMDB returns only its own user score, so formatCard() shows none known for ratings there. Read vote_average instead if you target TMDB.
Is the TMDB API free to use in a JavaScript app?
The TMDB API is free in a JavaScript app only until the app earns money, and amodb has no free tier.
According to TMDB staff on the TMDB forum (2026-10-15), an app is commercial once it earns revenue from ads, in-app purchases, donations or subscriptions. TMDB's commercial plan costs $149 a month for companies under $1M revenue, with a custom quote above that (TMDB staff, 2026-03-31). TMDB's API terms also require its logo plus a not-endorsed notice, and they say TMDB may end the license at any time. amodb starts at $5.19 a month, which is 3.5% of $149, charges nothing extra for commercial use and asks for no amodb logo or credit line. Third party credits still apply: credit JustWatch for where to watch data, and show the attribution credit wherever a text or image carries one. See TMDB API pricing for every plan. Sources read 2026-10-19.
What should I build next?
- Turn the loop into a small function that returns cards, then call it from an HTTP handler on your own server. Keep the key on the server. In a long running service, keep the
Mapin memory and skip the file, with a 6 hour TTL and expired entries deleted on read. - Swap the id list for TMDB trending API results and print a card for each.
- Add
moodsorsoundtrackstoappend_to_response. Moods arrive asmoods.results[]withname,avgandvalueson a 0 to 10 scale, andmoods.sourceismeasuredorestimated. Soundtracks arrive assoundtracks.results[], empty when no album is known. See the movie mood API and movie soundtrack API pages. - Compare the same task in TMDB API in Python, read the quickstart or browse all tutorials.