diff --git a/app/(site)/(root)/page.tsx b/app/(site)/(root)/page.tsx
index f30b8b4..1d802a8 100644
--- a/app/(site)/(root)/page.tsx
+++ b/app/(site)/(root)/page.tsx
@@ -1,5 +1,6 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { Metadata } from 'next';
+import Link from 'next/link';
import JsonLd from '@/components/JsonLd';
import randomQuery, { generatePage } from '@/data/queries/random';
@@ -24,6 +25,22 @@ const Random = async () => {
{TITLE} — Discover Your Next Favorite Movie
+
+ Discover your next favorite movie
+
+ {TITLE} helps you decide what to watch: spin through random movie recommendations right on this page, browse
+ the{' '}
+
+ most popular movies
+ {' '}
+ everyone is talking about, or dive into the{' '}
+
+ top-rated films
+ {' '}
+ of all time. Open any title to see its rating, overview, cast, and similar shows — and keep favorites and a
+ watchlist so you never lose track of what to watch next.
+
+
);
};
diff --git a/app/(site)/(show)/movie/[id]/page.tsx b/app/(site)/(show)/movie/[id]/page.tsx
index 534f96f..976a2fd 100644
--- a/app/(site)/(show)/movie/[id]/page.tsx
+++ b/app/(site)/(show)/movie/[id]/page.tsx
@@ -1,5 +1,7 @@
import { createShowMetadata, createShowPage } from '../../showPage';
+export const revalidate = 86400;
+
export const generateMetadata = createShowMetadata('movie');
const MoviePage = createShowPage('movie');
diff --git a/app/(site)/(show)/showPage.tsx b/app/(site)/(show)/showPage.tsx
index 1d964f2..5042e43 100644
--- a/app/(site)/(show)/showPage.tsx
+++ b/app/(site)/(show)/showPage.tsx
@@ -1,11 +1,12 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { Metadata } from 'next';
-import { notFound } from 'next/navigation';
+import { notFound, permanentRedirect } from 'next/navigation';
import JsonLd from '@/components/JsonLd';
import detailsQuery from '@/data/queries/details';
import { SITE_URL, TITLE } from '@/env';
import getQueryClient from '@/lib/queryClient';
+import { showPath } from '@/lib/utils';
import Container from './container';
@@ -18,22 +19,26 @@ export const createShowMetadata =
async ({ params: { id } }: Props): Promise => {
const queryClient = getQueryClient();
+ const showId = parseInt(id, 10);
+
+ if (!showId) return notFound();
+
try {
- const { title, overview, poster, backdrop } = await queryClient.fetchQuery(
- detailsQuery({ showId: Number(id), showType })
- );
+ const { title, overview, poster, backdrop } = await queryClient.fetchQuery(detailsQuery({ showId, showType }));
+
+ const path = showPath({ type: showType, id: showId, title });
return {
title: `${title} | ${TITLE}`,
description: overview,
- alternates: { canonical: `/${showType}/${id}` },
+ alternates: { canonical: path },
openGraph: {
title,
description: overview,
siteName: TITLE,
images: [backdrop || poster['2x']],
type: showType === 'movie' ? 'video.movie' : 'video.tv_show',
- url: `/${showType}/${id}`
+ url: path
}
};
} catch (_) {
@@ -45,12 +50,18 @@ export const createShowPage = (showType: Show['type']) => {
const ShowPage = async ({ params: { id } }: Props) => {
const queryClient = getQueryClient();
- const showId = Number(id);
+ const showId = parseInt(id, 10);
+
+ if (!showId) return notFound();
const details = await queryClient.fetchQuery(detailsQuery({ showId, showType })).catch(() => null);
if (!details) return notFound();
+ const path = showPath({ type: showType, id: showId, title: details.title });
+
+ if (decodeURIComponent(`/${showType}/${id}`) !== path) permanentRedirect(path);
+
const jsonLd = {
'@context': 'https://schema.org',
'@type': showType === 'movie' ? 'Movie' : 'TVSeries',
@@ -59,7 +70,7 @@ export const createShowPage = (showType: Show['type']) => {
image: details.poster['2x'] || undefined,
datePublished: details.release || undefined,
genre: details.genres?.map(({ name }) => name),
- url: `${SITE_URL}/${showType}/${showId}`,
+ url: `${SITE_URL}${path}`,
...(showType === 'movie' && details.runtime ? { duration: `PT${details.runtime}M` } : {}),
...(details.imdb_id ? { sameAs: `https://www.imdb.com/title/${details.imdb_id}/` } : {}),
...(details.votes
diff --git a/app/(site)/(show)/tv/[id]/page.tsx b/app/(site)/(show)/tv/[id]/page.tsx
index afb5e8b..eb6fc79 100644
--- a/app/(site)/(show)/tv/[id]/page.tsx
+++ b/app/(site)/(show)/tv/[id]/page.tsx
@@ -1,5 +1,7 @@
import { createShowMetadata, createShowPage } from '../../showPage';
+export const revalidate = 86400;
+
export const generateMetadata = createShowMetadata('tv');
const SeriesPage = createShowPage('tv');
diff --git a/app/(site)/person/[id]/page.tsx b/app/(site)/person/[id]/page.tsx
index acf722a..308bad9 100644
--- a/app/(site)/person/[id]/page.tsx
+++ b/app/(site)/person/[id]/page.tsx
@@ -13,6 +13,8 @@ interface Props {
params: { id: string };
}
+export const revalidate = 86400;
+
export const generateMetadata = async ({ params: { id } }: Props): Promise => {
const queryClient = getQueryClient();
diff --git a/app/server-sitemap.xml/route.ts b/app/server-sitemap.xml/route.ts
index c476848..6d7579c 100644
--- a/app/server-sitemap.xml/route.ts
+++ b/app/server-sitemap.xml/route.ts
@@ -1,6 +1,7 @@
import { getServerSideSitemap, ISitemapField } from 'next-sitemap';
import { MOVIE_DB_API_URL, MOVIE_DB_TOKEN, SITE_URL } from '@/env';
+import { showPath } from '@/lib/utils';
export const revalidate = 86400;
@@ -15,9 +16,12 @@ const DISCOVER_FILTERS = {
'vote_average.lte': '10'
};
-type TMDBListResponse = { results?: { id: number }[] };
+type TMDBListItem = { id: number; title?: string; name?: string };
+type TMDBListResponse = { results?: TMDBListItem[] };
-const fetchIds = async (path: string, params: Record): Promise => {
+type Entry = { id: number; title: string };
+
+const fetchEntries = async (path: string, params: Record): Promise => {
const query = new URLSearchParams(params).toString();
const response = await fetch(`${MOVIE_DB_API_URL}/${path}?${query}`, {
@@ -29,38 +33,42 @@ const fetchIds = async (path: string, params: Record): Promise id);
+ return results.map(({ id, title, name }) => ({ id, title: title || name || '' }));
};
// TMDB allows ~50 requests per second, so the task list is drained in small batches
-const collectIds = async (tasks: (() => Promise)[]) => {
- const ids: number[] = [];
+const collectEntries = async (tasks: (() => Promise)[]) => {
+ const entries = new Map();
for (let index = 0; index < tasks.length; index += BATCH_SIZE) {
const batch = await Promise.all(tasks.slice(index, index + BATCH_SIZE).map((task) => task().catch(() => [])));
- ids.push(...batch.flat());
+ batch.flat().forEach(({ id, title }) => entries.has(id) || entries.set(id, title));
}
- return Array.from(new Set(ids));
+ return Array.from(entries, ([id, title]) => ({ id, title }));
};
const pages = (count: number) => Array.from({ length: count }, (_, index) => `${index + 1}`);
const discoverTasks = (type: Show['type']) =>
['popularity.desc', 'vote_average.desc'].flatMap((sortBy) =>
- pages(LIST_PAGES).map((page) => () => fetchIds(`discover/${type}`, { ...DISCOVER_FILTERS, sort_by: sortBy, page }))
+ pages(LIST_PAGES).map(
+ (page) => () => fetchEntries(`discover/${type}`, { ...DISCOVER_FILTERS, sort_by: sortBy, page })
+ )
);
export async function GET() {
- const movieIds = await collectIds(discoverTasks('movie'));
- const seriesIds = await collectIds(discoverTasks('tv'));
- const personIds = await collectIds(pages(PERSON_PAGES).map((page) => () => fetchIds('person/popular', { page })));
+ const movies = await collectEntries(discoverTasks('movie'));
+ const series = await collectEntries(discoverTasks('tv'));
+ const persons = await collectEntries(
+ pages(PERSON_PAGES).map((page) => () => fetchEntries('person/popular', { page }))
+ );
const fields: ISitemapField[] = [
- ...movieIds.map((id) => `${SITE_URL}/movie/${id}`),
- ...seriesIds.map((id) => `${SITE_URL}/tv/${id}`),
- ...personIds.map((id) => `${SITE_URL}/person/${id}`)
+ ...movies.map(({ id, title }) => `${SITE_URL}${showPath({ type: 'movie', id, title })}`),
+ ...series.map(({ id, title }) => `${SITE_URL}${showPath({ type: 'tv', id, title })}`),
+ ...persons.map(({ id }) => `${SITE_URL}/person/${id}`)
].map((loc) => ({ loc }));
return getServerSideSitemap(fields);
diff --git a/components/List/index.tsx b/components/List/index.tsx
index 281f502..5d055fe 100644
--- a/components/List/index.tsx
+++ b/components/List/index.tsx
@@ -3,6 +3,7 @@ import { VirtuosoGrid, VirtuosoGridProps } from 'react-virtuoso';
import Poster from '@/components/Poster';
import { showPreviewModal } from '@/components/Preview';
+import { showPath } from '@/lib/utils';
interface Props {
shows: Show[];
@@ -18,7 +19,7 @@ const components: VirtuosoGridProps onClick?.(show)} />;
+ return onClick?.(show)} />;
}
};
diff --git a/components/Preview/components/Actions/index.tsx b/components/Preview/components/Actions/index.tsx
index 8fe84df..b20e73c 100644
--- a/components/Preview/components/Actions/index.tsx
+++ b/components/Preview/components/Actions/index.tsx
@@ -6,7 +6,7 @@ import { Button } from '@/components/ui/button';
import ButtonsGroup from '@/components/ui/buttons-group';
import useShowState, { useMutateShowState } from '@/hooks/useShowState';
import { useToast } from '@/hooks/useToast';
-import { cn } from '@/lib/utils';
+import { cn, showPath } from '@/lib/utils';
interface Props {
show: Show & Partial;
@@ -27,7 +27,7 @@ const Actions = ({ show, className, externalLink }: Props) => {
className='h-8 px-3'
onClick={() =>
navigator.clipboard
- .writeText(`${location.origin}/${show.type}/${show.id}`)
+ .writeText(`${location.origin}${showPath(show)}`)
.then(() => toast({ description: 'Link has been copied' }))
}
>
@@ -75,7 +75,7 @@ const Actions = ({ show, className, externalLink }: Props) => {
title='Open in new tab'
variant='outline'
className='relative h-8 px-3'
- onClick={() => window.open(`${location.origin}/${show.type}/${show.id}`, '_blank')}
+ onClick={() => window.open(`${location.origin}${showPath(show)}`, '_blank')}
>
diff --git a/components/Trending/components/Gallery/index.tsx b/components/Trending/components/Gallery/index.tsx
index 77ccc3e..79ce42b 100644
--- a/components/Trending/components/Gallery/index.tsx
+++ b/components/Trending/components/Gallery/index.tsx
@@ -5,6 +5,7 @@ import { FC } from 'react';
import Poster from '@/components/Poster';
import { showPreviewModal } from '@/components/Preview';
import ScrollNavigation from '@/components/ScrollNavigation';
+import { showPath } from '@/lib/utils';
interface Props {
shows: Show[];
@@ -24,7 +25,7 @@ const Gallery: FC = ({ shows }) => (
showPreviewModal({ show })}
/>
diff --git a/lib/queryClient.ts b/lib/queryClient.ts
index bd7403f..f0f8b0d 100644
--- a/lib/queryClient.ts
+++ b/lib/queryClient.ts
@@ -1,3 +1,4 @@
+import { cache } from 'react';
import { isServer, QueryClient } from '@tanstack/react-query';
const makeQueryClient = () => {
@@ -15,8 +16,20 @@ const makeQueryClient = () => {
let browserQueryClient: QueryClient | undefined = undefined;
+// One client per server request (React cache is request-scoped), so generateMetadata
+// and the page share fetches instead of hitting TMDB twice for the same data.
+const getServerQueryClient = cache(makeQueryClient);
+
const getQueryClient = () => {
- if (isServer) return makeQueryClient();
+ if (isServer) {
+ try {
+ return getServerQueryClient();
+ } catch (_) {
+ // cache() only works in the RSC runtime; the SSR pass of client components
+ // (e.g. Providers) lands here and keeps its own per-render client as before
+ return makeQueryClient();
+ }
+ }
if (!browserQueryClient) browserQueryClient = makeQueryClient();
diff --git a/lib/utils.ts b/lib/utils.ts
index f2d5f97..87a2376 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -3,6 +3,24 @@ import { twMerge } from 'tailwind-merge';
export const cn = (...inputs: ClassValue[]) => twMerge(clsx(inputs));
+export const slugify = (value: string) =>
+ value
+ .toLowerCase()
+ .normalize('NFKD')
+ .replace(/[̀-ͯ]/g, '')
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 60)
+ .replace(/-+$/, '');
+
+// Keyword-carrying show URL (/movie/27205-inception); the slug is optional decoration —
+// routing only relies on the leading numeric id.
+export const showPath = ({ type, id, title }: Pick) => {
+ const slug = slugify(title || '');
+
+ return `/${type}/${id}${slug ? `-${slug}` : ''}`;
+};
+
export const formatDate = (date: string) =>
new Intl.DateTimeFormat('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'UTC' })
.format(new Date(date))