Skip to main content

GET /api/tmdb

Fetch trending movies and TV shows for the current week from The Movie Database (TMDB). This endpoint returns curated content for display on the Connect World platform.
This endpoint fetches trending content from TMDB and returns the top 10 results. The data includes movies, TV shows, and their metadata for display in your application.

Rate Limiting

  • No rate limit - Public endpoint for content display

Request

No request body or parameters required. Simple GET request:
GET /api/tmdb

Response

movies
TmdbMovie[]
Array of trending movies and TV shows (limited to top 10)Each item contains full metadata from TMDB
error
string
Error message if TMDB fetch failsWhen error occurs, movies will be an empty array and this field contains the error details

TmdbMovie Schema

Each movie/show object in the response contains:

Example Request

curl -X GET https://your-domain.com/api/tmdb

Example Response

200 OK
{
  "movies": [
    {
      "id": 550,
      "title": "Fight Club",
      "poster_path": "/pB8BM7pdSp6B6Ih7QZ4DrQ3PmJK.jpg",
      "backdrop_path": "/fCayJrkfRaCRCTh8GqN30f8oyQF.jpg",
      "overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy.",
      "vote_average": 8.433,
      "release_date": "1999-10-15",
      "genre_ids": [18, 53, 35],
      "media_type": "movie"
    },
    {
      "id": 1396,
      "name": "Breaking Bad",
      "poster_path": "/3xnWaLQjelJDDF7LT1WBo6f4BRe.jpg",
      "backdrop_path": "/eSzpy96DwBujGFj0xMbXBcGcfxX.jpg",
      "overview": "When Walter White, a New Mexico chemistry teacher, is diagnosed with Stage III cancer...",
      "vote_average": 8.9,
      "first_air_date": "2008-01-20",
      "genre_ids": [18, 80],
      "media_type": "tv"
    }
  ]
}

Error Response

Image URLs

TMDB returns relative paths for images. Use the helper function to generate full URLs:
// From tmdbService.ts:44-47
export function getPosterUrl(path: string | null, size = 'w500'): string {
  if (!path) return '/images/placeholder.jpg';
  return `https://image.tmdb.org/t/p/${size}${path}`;
}

Available Image Sizes

Poster sizes:
  • w92 - Thumbnail
  • w154 - Small
  • w185 - Medium (default mobile)
  • w342 - Large
  • w500 - Extra large (recommended)
  • w780 - XXL
  • original - Full resolution
Backdrop sizes:
  • w300 - Small
  • w780 - Medium
  • w1280 - Large
  • original - Full resolution (recommended)

Example: Rendering Images

function MovieCard({ movie }) {
  const posterUrl = movie.poster_path
    ? `https://image.tmdb.org/t/p/w500${movie.poster_path}`
    : '/images/placeholder.jpg';
  
  const backdropUrl = movie.backdrop_path
    ? `https://image.tmdb.org/t/p/original${movie.backdrop_path}`
    : null;
  
  const title = movie.title || movie.name;
  const date = movie.release_date || movie.first_air_date;
  
  return (
    <div className="movie-card">
      <img src={posterUrl} alt={title} />
      <h3>{title}</h3>
      <p>Rating: {movie.vote_average}/10</p>
      <p>Release: {date}</p>
      <p>{movie.overview}</p>
    </div>
  );
}

TMDB Service

The endpoint uses the getTrendingAll function from the TMDB service:
// From tmdbService.ts:29-32
export async function getTrendingAll(timeWindow: 'day' | 'week' = 'week'): Promise<TmdbMovie[]> {
  const { data } = await tmdbClient.get<TmdbResponse>(`/trending/all/${timeWindow}`);
  return data.results.slice(0, 10);
}

Service Configuration

The TMDB service is configured with:
  • Base URL: https://api.themoviedb.org/3
  • Language: es-ES (Spanish)
  • Authentication: API key from environment variable
  • Default time window: week
  • Result limit: Top 10 items

Additional TMDB Functions

The TMDB service provides additional functions (not exposed via API routes):

Implementation Details

The endpoint is implemented in /src/app/api/tmdb/route.ts:4 and uses:
  • Service: tmdbService.getTrendingAll()
  • HTTP Client: axios with base configuration
  • Time Window: "week" (7 days of trending data)
  • Language: Spanish (es-ES) for localized titles
  • Error Handling: Returns empty array with error message on failure

Genre IDs Reference

Common TMDB genre IDs:
IDGenre
28Action
12Adventure
16Animation
35Comedy
80Crime
99Documentary
18Drama
10751Family
14Fantasy
36History
27Horror
10402Music
9648Mystery
10749Romance
878Science Fiction
10770TV Movie
53Thriller
10752War
37Western

Environment Variables

Required environment variable:
NEXT_PUBLIC_TMDB_API_KEY=your_tmdb_api_key_here
Get your TMDB API key from The Movie Database API. It’s free for non-commercial use.

Use Cases

Homepage Hero Section

Display trending content on your homepage:
import { useEffect, useState } from 'react';

function HeroSection() {
  const [trending, setTrending] = useState([]);
  
  useEffect(() => {
    fetch('/api/tmdb')
      .then(res => res.json())
      .then(data => setTrending(data.movies.slice(0, 5)));
  }, []);
  
  return (
    <div className="hero">
      {trending.map(item => (
        <div key={item.id} className="hero-slide">
          <img 
            src={`https://image.tmdb.org/t/p/original${item.backdrop_path}`}
            alt={item.title || item.name}
          />
        </div>
      ))}
    </div>
  );
}

Content Catalog

Build a browsable catalog of trending content:
function TrendingCatalog() {
  const [movies, setMovies] = useState([]);
  const [loading, setLoading] = useState(true);
  
  useEffect(() => {
    fetch('/api/tmdb')
      .then(res => res.json())
      .then(data => {
        setMovies(data.movies);
        setLoading(false);
      })
      .catch(err => {
        console.error('Failed to load trending:', err);
        setLoading(false);
      });
  }, []);
  
  if (loading) return <div>Loading trending content...</div>;
  
  return (
    <div className="catalog">
      <h2>Trending This Week</h2>
      <div className="grid">
        {movies.map(movie => (
          <MovieCard key={movie.id} movie={movie} />
        ))}
      </div>
    </div>
  );
}

Caching Recommendations

Consider implementing caching for TMDB data:
  • Client-side: Cache in localStorage or React Query
  • Server-side: Cache with Redis or in-memory cache
  • TTL: 6-12 hours (trending data changes slowly)
  • Benefit: Reduce TMDB API calls and improve response time

See Also

Build docs developers (and LLMs) love