Next.js movie app tutorial with the App Router
A Next.js movie app should call its API from server components, so the key never reaches the browser. This tutorial builds a three page site on Next.js 15 in plain JavaScript: trending, search and a movie page with IMDb, Kinopoisk and TMDB scores. It needs Node.js 18.18 and about 25 minutes.
To build a Next.js movie app, fetch the data in server components, so the API key stays on the server and the browser only receives HTML. This tutorial uses 3 calls: trending (1 request every 30 minutes), search (1 request per new query, cached for 10 minutes) and one details call with ratings per movie (cached for 6 hours). Posters cost 0 requests. If you already have a Next.js TMDB app, change the base URL to https:/ and the key, and keep your fetch calls.
What do you need to build a Next.js movie app?
You build a small movie site with three pages: a trending list on the home page, a search page and a movie page with IMDb, Kinopoisk and TMDB scores.
| You need | Value |
|---|---|
| Runtime | Node.js 18.18 or newer |
| Framework | Next.js 15 with the App Router, plain JavaScript, no TypeScript |
| Packages | 3: next, react and react-dom (React 19) |
| Key | An amodb key, 32 lowercase hex characters. The TMDB API key page shows how to get one |
| Plan | Any plan. Lite, at 20 requests per minute, is enough for a small site |
| Where the key lives | .env.local, server only, as AMODB_KEY |
| Time | About 25 minutes |
Which calls does the Next.js movie app make, and what do they cost?
Every call to the API costs 1 request, and a reply served from the edge cache counts too. A hit in the Next.js data cache never reaches amodb, so it costs 0 requests. Posters come from a separate host that needs no key and is not counted.
| Page | Call | Cost | revalidate |
|---|---|---|---|
| Home | GET / | 1 request per 30 minutes | 1800 seconds |
| Search | GET / | 1 request per new query per 10 minutes | 600 seconds |
| Movie | GET / | 1 request per movie per 6 hours | 21600 seconds |
| Posters | https:/ | 0 requests | handled by next/image |
On the 20 requests per minute plan, a site cannot pass 28,800 requests a day, and with these cache lifetimes most visits cost nothing. The TMDB trending API page lists other lists you can show on the home page, and the movie details API page explains append_to_response.
Step 1: Get an API key and keep it on the server
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 .env.local at the project root without the NEXT_PUBLIC_ prefix.
Every plan has every TMDB v3 compatible endpoint, images, 14 languages and the extensions. The plans differ in rate (Lite 20, Pro 40, Pro+ 120 requests per minute, from $5.19 a month), and only Pro+ also has the all in one endpoint GET /. There is no free tier or trial. Open .env.local and add the key:
Do not prefix the name with NEXT_PUBLIC_. Next.js copies variables with that prefix into the browser bundle, and a plain name stays on the server. Restart the dev server after you change the file, and add .env.local to .gitignore before the first commit. The authentication page describes the header and query forms of the key.
AMODB_KEY=YOUR_API_KEYStep 2: Create the project
Create package.json, install the packages and add the image host to next.config.js.
{
"name": "movie-finder",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"next": "^15.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
}
}Install the packages:
npm installPosters live on img.amodb.dev, and next/image only loads hosts you list. The pathname pattern limits it to the poster path.
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
remotePatterns: [
{ protocol: 'https', hostname: 'img.amodb.dev', pathname: '/t/p/**' },
],
},
};
module.exports = nextConfig;Step 3: Write the fetch helper
Write one function in lib/amodb.js that adds the Bearer header, a 10 second timeout and the revalidate option to every call.
The revalidate option tells Next.js how long it may reuse the answer. Next.js 15 does not cache fetch by default, so the option is what turns the cache on.
The path starts with a slash and is added to the base, so /3 stays in the URL. A 404 returns null, so a page can call notFound(). The retry waits at most 10 seconds because a visitor is waiting for the page.
const BASE = 'https://api.amodb.dev/3';
export async function amodb(path, { params = {}, revalidate = 21600 } = {}) {
const key = process.env.AMODB_KEY;
if (!key) throw new Error('AMODB_KEY is not set');
const url = new URL(BASE + path);
for (const [name, value] of Object.entries(params)) url.searchParams.set(name, value);
for (let attempt = 0; ; attempt++) {
const res = await fetch(url.toString(), {
headers: { Authorization: `Bearer ${key}` },
next: { revalidate },
signal: AbortSignal.timeout(10000),
});
if (res.status === 429 && attempt < 2) {
const seconds = Math.min(Number(res.headers.get('retry-after')) || 5, 10);
await new Promise((resolve) => setTimeout(resolve, seconds * 1000));
continue;
}
if (res.status === 401) throw new Error('amodb rejected the API key (401)');
if (res.status === 404) return null;
if (!res.ok) throw new Error(`amodb returned ${res.status}`);
return res.json();
}
}Step 4: Build the pages
Create the layout, a poster grid and three pages, and call the fetch helper from each page, because every page is a server component.
Start with the layout. It holds the search form, a plain GET form that sends q to /search.
import Link from 'next/link';
export const metadata = {
title: 'Movie finder',
description: 'Trending movies and search, powered by the amodb API.',
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body style={{ margin: 0, fontFamily: 'system-ui, sans-serif' }}>
<header style={{ padding: 16, background: '#111', color: '#fff' }}>
<Link href="/" style={{ color: '#fff', marginRight: 16 }}>Movie finder</Link>
<form action="/search" style={{ display: 'inline' }}>
<input name="q" placeholder="Search movies" />
<button type="submit">Search</button>
</form>
</header>
<main style={{ maxWidth: 960, margin: '0 auto', padding: 16 }}>{children}</main>
</body>
</html>
);
}The poster grid in components/ serves the home page and the search page. A poster URL is https:/ plus the poster_path value. See the TMDB image URL page for the sizes.
import Image from 'next/image';
import Link from 'next/link';
export default function MovieGrid({ movies }) {
if (movies.length === 0) return <p>No movies found.</p>;
return (
<ul style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))', gap: 16, padding: 0, listStyle: 'none' }}>
{movies.map((movie) => (
<li key={movie.id}>
<Link href={`/movie/${movie.id}`}>
{movie.poster_path && (
<Image
src={`https://img.amodb.dev/t/p/w342${movie.poster_path}`}
alt={movie.title}
width={342}
height={513}
style={{ width: '100%', height: 'auto' }}
/>
)}
<strong>{movie.title}</strong>
</Link>
<div>{(movie.release_date || '').slice(0, 4)}</div>
</li>
))}
</ul>
);
}The home page in app/page.js is an async server component. It reads this week's trending movies, described on the TMDB trending API page.
import MovieGrid from '../components/MovieGrid';
import { amodb } from '../lib/amodb';
export default async function Home() {
const data = await amodb('/trending/movie/week', {
params: { language: 'en-US' },
revalidate: 1800,
});
return (
<section>
<h1>Trending this week</h1>
<MovieGrid movies={data.results.slice(0, 18)} />
</section>
);
}In Next.js 15, searchParams and params are promises, so each page awaits them. The search page in app/search/page.js uses the TMDB search API.
import MovieGrid from '../../components/MovieGrid';
import { amodb } from '../../lib/amodb';
export default async function SearchPage({ searchParams }) {
const { q } = await searchParams;
const query = (Array.isArray(q) ? q[0] : (q ?? '')).trim();
if (!query) return <p>Type a title in the box above.</p>;
const data = await amodb('/search/movie', {
params: { query, language: 'en-US' },
revalidate: 600,
});
return (
<section>
<h1>Results for {query}</h1>
<MovieGrid movies={data.results} />
</section>
);
}The movie page in app/movie/[id]/page.js requests one movie with append_, so details and scores arrive in a single call. Each source is { value, votes } or null. A null source means the score is not known, and a null votes hides the vote count, so the page says "not known" or prints only the value. For movie 550 it shows 8.8 (2,669,989 votes) for IMDb, 8.7 for Kinopoisk and 8.437 (33,039 votes) for TMDB. The movie ratings API page explains all five sources.
import Image from 'next/image';
import { notFound } from 'next/navigation';
import { amodb } from '../../../lib/amodb';
function score(source) {
if (!source) return 'not known';
const votes = source.votes ? ` (${source.votes.toLocaleString('en-US')} votes)` : '';
return `${source.value}${votes}`;
}
export default async function MoviePage({ params }) {
const { id } = await params;
if (!/^\d+$/.test(id)) notFound();
const movie = await amodb(`/movie/${id}`, {
params: { language: 'en-US', append_to_response: 'ratings' },
});
if (!movie) notFound();
return (
<article style={{ display: 'flex', gap: 24, flexWrap: 'wrap' }}>
{movie.poster_path && (
<Image src={`https://img.amodb.dev/t/p/w500${movie.poster_path}`} alt={movie.title} width={300} height={450} priority />
)}
<div style={{ flex: 1, minWidth: 260 }}>
<h1>{movie.title} ({(movie.release_date || '').slice(0, 4)})</h1>
{movie.tagline && <p><em>{movie.tagline}</em></p>}
<p>{movie.overview}</p>
<ul>
<li>Runtime: {movie.runtime ? `${movie.runtime} min` : 'not known'}</li>
<li>IMDb: {score(movie.ratings?.imdb)}</li>
<li>Kinopoisk: {score(movie.ratings?.kinopoisk)}</li>
<li>TMDB: {score(movie.ratings?.tmdb)}</li>
</ul>
</div>
</article>
);
}Step 5: Handle errors and rate limits
Let the helper throw on failures, so that Next.js shows the closest error.js file.
| Status | Meaning | What the app does |
|---|---|---|
| 401 | Key missing or invalid (status_code 7 for an invalid key) | The helper throws, error.js renders, the cause is in the server log. |
| 402 | The plan period has ended (status_code 36) | Same path. Renew on amodb pricing. |
| 404 | No record for that id | The helper returns null and the page calls notFound(). |
| 429 | Over your requests per minute (status_code 25) | Wait Retry-After seconds, capped at 10, retry twice, then throw. |
| 500 or 504 | Server side failure | The helper throws and error.js renders. |
An error boundary must be a client component. In production Next.js hides the error message from the browser and prints it in the server log, so a rejected key shows up in your terminal and not on the page. Create app/error.js and app/not-found.js:
'use client';
export default function ErrorPage({ reset }) {
return (
<div>
<h2>The movie service did not answer</h2>
<p>Try again in a moment.</p>
<button onClick={() => reset()}>Try again</button>
</div>
);
}The not-found page is one component:
The error codes page lists every status code, and the TMDB API rate limit page explains the X-RateLimit-Remaining and Retry-After headers.
export default function NotFound() {
return <p>That movie does not exist.</p>;
}Step 6: Cache with revalidate
Set revalidate on each call to the edge cache lifetime, so a page never refreshes faster than the data changes.
A hit in the Next.js data cache never calls amodb, so it also costs no requests per minute. A call that reaches amodb is counted even when the edge cache answers it, so the Next.js cache is the one that saves requests.
| Page | revalidate in seconds | Edge cache lifetime |
|---|---|---|
| Home, trending | 1800 | 30 minutes |
| Search | 600 | 10 minutes |
| Movie details | 21600 | 6 hours |
The home page has no dynamic input, so next build renders it once and refreshes it in the background every 30 minutes. That build calls amodb, so AMODB_KEY must be set in the build environment too.
Step 7: Run and check
Run npm run dev and open the local address that Next.js prints.
The home page shows posters, the search box finds titles and a poster opens its movie page. For a production run use npm run build and npm run start. The project now has these files:
| File | Role |
|---|---|
package.json | The three dependencies and the scripts. |
.env.local | The key, server only. |
next.config.js | Allows img.amodb.dev for next/image. |
lib/amodb.js | Fetch helper with timeout, 401, 404 and 429 handling. |
components/ | Poster grid for the home and search pages. |
app/layout.js | Page shell and search form. |
app/page.js | Trending list. |
app/search/page.js | Search results. |
app/movie/[id]/page.js | Movie details with ratings. |
app/error.js, app/not-found.js | Failure and missing id pages. |
npm run devIs the TMDB API free to use in a Next.js movie app?
The TMDB API is free only while your app earns nothing, and a movie site with ads, subscriptions or donations needs a paid plan.
TMDB staff said on the TMDB forum (2026-10-15) that an app counts as commercial the moment it earns revenue from ads, in-app purchases, donations or subscriptions. They quoted the commercial plan at $149 a month for companies under $1M revenue, with a custom quote above (2026-03-31), and there is no small tier between free and $149. TMDB's terms of use also require its logo with a not-endorsed notice and limit caching to 6 months.
| Project | TMDB | amodb |
|---|---|---|
| Personal site, earns nothing | Free under TMDB's terms | Paid, from $5.19 a month, no free tier |
| Commercial site (ads, subscriptions, donations) | $149 a month under $1M revenue, custom quote above | From $5.19 a month. No extra charge; the terms do not prohibit it |
| Logo or attribution | TMDB logo and notice required | No amodb logo; credit JustWatch and licensed texts and images as marked |
amodb plans cost $5.19, $6.19 or $7.19 a month, which is 3.5% to 4.8% of $149, and longer periods save up to 40 percent. Pay by card, Apple Pay or Google Pay, prepaid for 1, 3, 6, 12 or 24 months; those payments do not renew automatically. Patreon is monthly and renews on Patreon until the member cancels there. Do not resell raw API access or share keys. Read Is the TMDB API free? for the full comparison.
Next steps
- Add a
generateMetadatafunction to the movie page so every title gets its own page title. Next.js reuses the same fetch call. - Show cast with
append_, described on the credits API page.to_ response= credits - Switch
languageto a visitor's language, using the 14 base languages on the language codes page. - Read the same task for a phone in the TMDB API in Swift tutorial, or the same calls in TMDB API in JavaScript.
- Start from the quickstart for a first request, and browse every guide in the tutorials hub.