feat(seo): slugged show urls, sr-only homepage intro, ISR detail pages

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
nerandClaude Fable 5 committed 2026-08-07 17:46:01 +03:00
1 parent ce630cd029
commit 735c63471a
11 files changed
+103 -28

No files matched your search

+17
View File
@@ -1,5 +1,6 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query'; import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { Metadata } from 'next'; import { Metadata } from 'next';
import Link from 'next/link';
import JsonLd from '@/components/JsonLd'; import JsonLd from '@/components/JsonLd';
import randomQuery, { generatePage } from '@/data/queries/random'; import randomQuery, { generatePage } from '@/data/queries/random';
@@ -24,6 +25,22 @@ const Random = async () => {
<JsonLd data={{ '@context': 'https://schema.org', '@type': 'WebSite', name: TITLE, url: SITE_URL }} /> <JsonLd data={{ '@context': 'https://schema.org', '@type': 'WebSite', name: TITLE, url: SITE_URL }} />
<h1 className='sr-only'>{TITLE} — Discover Your Next Favorite Movie</h1> <h1 className='sr-only'>{TITLE} — Discover Your Next Favorite Movie</h1>
<Container page={page} /> <Container page={page} />
<section className='sr-only'>
<h2>Discover your next favorite movie</h2>
<p>
{TITLE} helps you decide what to watch: spin through random movie recommendations right on this page, browse
the{' '}
<Link className='underline underline-offset-2' href='/popular'>
most popular movies
</Link>{' '}
everyone is talking about, or dive into the{' '}
<Link className='underline underline-offset-2' href='/top'>
top-rated films
</Link>{' '}
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.
</p>
</section>
</HydrationBoundary> </HydrationBoundary>
); );
}; };
+2
View File
@@ -1,5 +1,7 @@
import { createShowMetadata, createShowPage } from '../../showPage'; import { createShowMetadata, createShowPage } from '../../showPage';
export const revalidate = 86400;
export const generateMetadata = createShowMetadata('movie'); export const generateMetadata = createShowMetadata('movie');
const MoviePage = createShowPage('movie'); const MoviePage = createShowPage('movie');
+19 -8
View File
@@ -1,11 +1,12 @@
import { dehydrate, HydrationBoundary } from '@tanstack/react-query'; import { dehydrate, HydrationBoundary } from '@tanstack/react-query';
import { Metadata } from 'next'; import { Metadata } from 'next';
import { notFound } from 'next/navigation'; import { notFound, permanentRedirect } from 'next/navigation';
import JsonLd from '@/components/JsonLd'; import JsonLd from '@/components/JsonLd';
import detailsQuery from '@/data/queries/details'; import detailsQuery from '@/data/queries/details';
import { SITE_URL, TITLE } from '@/env'; import { SITE_URL, TITLE } from '@/env';
import getQueryClient from '@/lib/queryClient'; import getQueryClient from '@/lib/queryClient';
import { showPath } from '@/lib/utils';
import Container from './container'; import Container from './container';
@@ -18,22 +19,26 @@ export const createShowMetadata =
async ({ params: { id } }: Props): Promise<Metadata> => { async ({ params: { id } }: Props): Promise<Metadata> => {
const queryClient = getQueryClient(); const queryClient = getQueryClient();
const showId = parseInt(id, 10);
if (!showId) return notFound();
try { try {
const { title, overview, poster, backdrop } = await queryClient.fetchQuery( const { title, overview, poster, backdrop } = await queryClient.fetchQuery(detailsQuery({ showId, showType }));
detailsQuery({ showId: Number(id), showType })
); const path = showPath({ type: showType, id: showId, title });
return { return {
title: `${title} | ${TITLE}`, title: `${title} | ${TITLE}`,
description: overview, description: overview,
alternates: { canonical: `/${showType}/${id}` }, alternates: { canonical: path },
openGraph: { openGraph: {
title, title,
description: overview, description: overview,
siteName: TITLE, siteName: TITLE,
images: [backdrop || poster['2x']], images: [backdrop || poster['2x']],
type: showType === 'movie' ? 'video.movie' : 'video.tv_show', type: showType === 'movie' ? 'video.movie' : 'video.tv_show',
url: `/${showType}/${id}` url: path
} }
}; };
} catch (_) { } catch (_) {
@@ -45,12 +50,18 @@ export const createShowPage = (showType: Show['type']) => {
const ShowPage = async ({ params: { id } }: Props) => { const ShowPage = async ({ params: { id } }: Props) => {
const queryClient = getQueryClient(); 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); const details = await queryClient.fetchQuery(detailsQuery({ showId, showType })).catch(() => null);
if (!details) return notFound(); if (!details) return notFound();
const path = showPath({ type: showType, id: showId, title: details.title });
if (decodeURIComponent(`/${showType}/${id}`) !== path) permanentRedirect(path);
const jsonLd = { const jsonLd = {
'@context': 'https://schema.org', '@context': 'https://schema.org',
'@type': showType === 'movie' ? 'Movie' : 'TVSeries', '@type': showType === 'movie' ? 'Movie' : 'TVSeries',
@@ -59,7 +70,7 @@ export const createShowPage = (showType: Show['type']) => {
image: details.poster['2x'] || undefined, image: details.poster['2x'] || undefined,
datePublished: details.release || undefined, datePublished: details.release || undefined,
genre: details.genres?.map(({ name }) => name), genre: details.genres?.map(({ name }) => name),
url: `${SITE_URL}/${showType}/${showId}`, url: `${SITE_URL}${path}`,
...(showType === 'movie' && details.runtime ? { duration: `PT${details.runtime}M` } : {}), ...(showType === 'movie' && details.runtime ? { duration: `PT${details.runtime}M` } : {}),
...(details.imdb_id ? { sameAs: `https://www.imdb.com/title/${details.imdb_id}/` } : {}), ...(details.imdb_id ? { sameAs: `https://www.imdb.com/title/${details.imdb_id}/` } : {}),
...(details.votes ...(details.votes
+2
View File
@@ -1,5 +1,7 @@
import { createShowMetadata, createShowPage } from '../../showPage'; import { createShowMetadata, createShowPage } from '../../showPage';
export const revalidate = 86400;
export const generateMetadata = createShowMetadata('tv'); export const generateMetadata = createShowMetadata('tv');
const SeriesPage = createShowPage('tv'); const SeriesPage = createShowPage('tv');
+2
View File
@@ -13,6 +13,8 @@ interface Props {
params: { id: string }; params: { id: string };
} }
export const revalidate = 86400;
export const generateMetadata = async ({ params: { id } }: Props): Promise<Metadata> => { export const generateMetadata = async ({ params: { id } }: Props): Promise<Metadata> => {
const queryClient = getQueryClient(); const queryClient = getQueryClient();
+22 -14
View File
@@ -1,6 +1,7 @@
import { getServerSideSitemap, ISitemapField } from 'next-sitemap'; import { getServerSideSitemap, ISitemapField } from 'next-sitemap';
import { MOVIE_DB_API_URL, MOVIE_DB_TOKEN, SITE_URL } from '@/env'; import { MOVIE_DB_API_URL, MOVIE_DB_TOKEN, SITE_URL } from '@/env';
import { showPath } from '@/lib/utils';
export const revalidate = 86400; export const revalidate = 86400;
@@ -15,9 +16,12 @@ const DISCOVER_FILTERS = {
'vote_average.lte': '10' '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<string, string>): Promise<number[]> => { type Entry = { id: number; title: string };
const fetchEntries = async (path: string, params: Record<string, string>): Promise<Entry[]> => {
const query = new URLSearchParams(params).toString(); const query = new URLSearchParams(params).toString();
const response = await fetch(`${MOVIE_DB_API_URL}/${path}?${query}`, { const response = await fetch(`${MOVIE_DB_API_URL}/${path}?${query}`, {
@@ -29,38 +33,42 @@ const fetchIds = async (path: string, params: Record<string, string>): Promise<n
const { results = [] }: TMDBListResponse = await response.json(); const { results = [] }: TMDBListResponse = await response.json();
return results.map(({ id }) => 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 // TMDB allows ~50 requests per second, so the task list is drained in small batches
const collectIds = async (tasks: (() => Promise<number[]>)[]) => { const collectEntries = async (tasks: (() => Promise<Entry[]>)[]) => {
const ids: number[] = []; const entries = new Map<number, string>();
for (let index = 0; index < tasks.length; index += BATCH_SIZE) { 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(() => []))); 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 pages = (count: number) => Array.from({ length: count }, (_, index) => `${index + 1}`);
const discoverTasks = (type: Show['type']) => const discoverTasks = (type: Show['type']) =>
['popularity.desc', 'vote_average.desc'].flatMap((sortBy) => ['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() { export async function GET() {
const movieIds = await collectIds(discoverTasks('movie')); const movies = await collectEntries(discoverTasks('movie'));
const seriesIds = await collectIds(discoverTasks('tv')); const series = await collectEntries(discoverTasks('tv'));
const personIds = await collectIds(pages(PERSON_PAGES).map((page) => () => fetchIds('person/popular', { page }))); const persons = await collectEntries(
pages(PERSON_PAGES).map((page) => () => fetchEntries('person/popular', { page }))
);
const fields: ISitemapField[] = [ const fields: ISitemapField[] = [
...movieIds.map((id) => `${SITE_URL}/movie/${id}`), ...movies.map(({ id, title }) => `${SITE_URL}${showPath({ type: 'movie', id, title })}`),
...seriesIds.map((id) => `${SITE_URL}/tv/${id}`), ...series.map(({ id, title }) => `${SITE_URL}${showPath({ type: 'tv', id, title })}`),
...personIds.map((id) => `${SITE_URL}/person/${id}`) ...persons.map(({ id }) => `${SITE_URL}/person/${id}`)
].map((loc) => ({ loc })); ].map((loc) => ({ loc }));
return getServerSideSitemap(fields); return getServerSideSitemap(fields);
+2 -1
View File
@@ -3,6 +3,7 @@ import { VirtuosoGrid, VirtuosoGridProps } from 'react-virtuoso';
import Poster from '@/components/Poster'; import Poster from '@/components/Poster';
import { showPreviewModal } from '@/components/Preview'; import { showPreviewModal } from '@/components/Preview';
import { showPath } from '@/lib/utils';
interface Props { interface Props {
shows: Show[]; shows: Show[];
@@ -18,7 +19,7 @@ const components: VirtuosoGridProps<Movie, { shows: Show[]; onClick: (show: Show
if (!show) return null; if (!show) return null;
return <Poster show={show} href={`/${show.type}/${show.id}`} onClick={() => onClick?.(show)} />; return <Poster show={show} href={showPath(show)} onClick={() => onClick?.(show)} />;
} }
}; };
@@ -6,7 +6,7 @@ import { Button } from '@/components/ui/button';
import ButtonsGroup from '@/components/ui/buttons-group'; import ButtonsGroup from '@/components/ui/buttons-group';
import useShowState, { useMutateShowState } from '@/hooks/useShowState'; import useShowState, { useMutateShowState } from '@/hooks/useShowState';
import { useToast } from '@/hooks/useToast'; import { useToast } from '@/hooks/useToast';
import { cn } from '@/lib/utils'; import { cn, showPath } from '@/lib/utils';
interface Props { interface Props {
show: Show & Partial<Details>; show: Show & Partial<Details>;
@@ -27,7 +27,7 @@ const Actions = ({ show, className, externalLink }: Props) => {
className='h-8 px-3' className='h-8 px-3'
onClick={() => onClick={() =>
navigator.clipboard navigator.clipboard
.writeText(`${location.origin}/${show.type}/${show.id}`) .writeText(`${location.origin}${showPath(show)}`)
.then(() => toast({ description: 'Link has been copied' })) .then(() => toast({ description: 'Link has been copied' }))
} }
> >
@@ -75,7 +75,7 @@ const Actions = ({ show, className, externalLink }: Props) => {
title='Open in new tab' title='Open in new tab'
variant='outline' variant='outline'
className='relative h-8 px-3' className='relative h-8 px-3'
onClick={() => window.open(`${location.origin}/${show.type}/${show.id}`, '_blank')} onClick={() => window.open(`${location.origin}${showPath(show)}`, '_blank')}
> >
<ExternalLink size={14} /> <ExternalLink size={14} />
</Button> </Button>
@@ -5,6 +5,7 @@ import { FC } from 'react';
import Poster from '@/components/Poster'; import Poster from '@/components/Poster';
import { showPreviewModal } from '@/components/Preview'; import { showPreviewModal } from '@/components/Preview';
import ScrollNavigation from '@/components/ScrollNavigation'; import ScrollNavigation from '@/components/ScrollNavigation';
import { showPath } from '@/lib/utils';
interface Props { interface Props {
shows: Show[]; shows: Show[];
@@ -24,7 +25,7 @@ const Gallery: FC<Props> = ({ shows }) => (
<Poster <Poster
className='!h-[350px] !w-[230px] text-sm' className='!h-[350px] !w-[230px] text-sm'
show={show} show={show}
href={`/${show.type}/${show.id}`} href={showPath(show)}
onClick={() => showPreviewModal({ show })} onClick={() => showPreviewModal({ show })}
/> />
</li> </li>
+14 -1
View File
@@ -1,3 +1,4 @@
import { cache } from 'react';
import { isServer, QueryClient } from '@tanstack/react-query'; import { isServer, QueryClient } from '@tanstack/react-query';
const makeQueryClient = () => { const makeQueryClient = () => {
@@ -15,8 +16,20 @@ const makeQueryClient = () => {
let browserQueryClient: QueryClient | undefined = undefined; 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 = () => { 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(); if (!browserQueryClient) browserQueryClient = makeQueryClient();
+18
View File
@@ -3,6 +3,24 @@ import { twMerge } from 'tailwind-merge';
export const cn = (...inputs: ClassValue[]) => twMerge(clsx(inputs)); 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<Show, 'type' | 'id' | 'title'>) => {
const slug = slugify(title || '');
return `/${type}/${id}${slug ? `-${slug}` : ''}`;
};
export const formatDate = (date: string) => export const formatDate = (date: string) =>
new Intl.DateTimeFormat('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'UTC' }) new Intl.DateTimeFormat('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric', timeZone: 'UTC' })
.format(new Date(date)) .format(new Date(date))