SEO, метаданные, изображения и шрифты

То, ради чего чаще всего и берут Next.js. Здесь он даёт больше готового, чем любой другой фреймворк.

Статические метаданные

// app/layout.tsx
import type { Metadata } from 'next';

export const metadata: Metadata = {
  metadataBase: new URL('https://example.ru'),
  title: {
    default: 'Магазин инструментов',
    template: '%s — Магазин инструментов',   // подставится в дочерних страницах
  },
  description: 'Профессиональный инструмент с доставкой по России',
  keywords: ['инструмент', 'доставка'],
  openGraph: {
    type: 'website',
    locale: 'ru_RU',
    siteName: 'Магазин инструментов',
    images: ['/og-default.png'],
  },
  twitter: { card: 'summary_large_image' },
  robots: { index: true, follow: true },
  alternates: { canonical: '/' },
};

Динамические метаданные

// app/products/[slug]/page.tsx
export async function generateMetadata({ params }): Promise<Metadata> {
  const { slug } = await params;
  const product = await getProduct(slug);

  if (!product) return { title: 'Товар не найден' };

  return {
    title: product.title,
    description: product.shortDescription,
    openGraph: {
      title: product.title,
      description: product.shortDescription,
      images: [{ url: product.image, width: 1200, height: 630 }],
    },
    alternates: { canonical: `/products/${slug}` },
  };
}
💡 Совет
Запрос данных в generateMetadata и в самом компоненте страницы дедуплицируется — тот же fetch выполнится один раз. Дублировать запрос не страшно.

Генерация OG-картинки

// app/products/[slug]/opengraph-image.tsx
import { ImageResponse } from 'next/og';

export const size = { width: 1200, height: 630 };
export const contentType = 'image/png';

export default async function Image({ params }) {
  const product = await getProduct(params.slug);

  return new ImageResponse(
    (
      <div style={{
        display: 'flex', flexDirection: 'column', justifyContent: 'center',
        width: '100%', height: '100%', background: '#14171d',
        color: '#fff', padding: 80, fontSize: 64,
      }}>
        <div>{product.title}</div>
        <div style={{ fontSize: 36, color: '#8b93a7' }}>{product.price} ₽</div>
      </div>
    ),
    size
  );
}

Карта сайта и robots

// app/sitemap.ts
import type { MetadataRoute } from 'next';

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const products = await db.product.findMany({
    select: { slug: true, updatedAt: true },
  });

  return [
    { url: 'https://example.ru', lastModified: new Date(), priority: 1 },
    ...products.map(p => ({
      url: `https://example.ru/products/${p.slug}`,
      lastModified: p.updatedAt,
      changeFrequency: 'weekly' as const,
      priority: 0.8,
    })),
  ];
}

// app/robots.ts
export default function robots(): MetadataRoute.Robots {
  return {
    rules: [{ userAgent: '*', allow: '/', disallow: ['/admin', '/api'] }],
    sitemap: 'https://example.ru/sitemap.xml',
  };
}

Структурированные данные

export default async function ProductPage({ params }) {
  const product = await getProduct((await params).slug);

  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'Product',
    name: product.title,
    image: product.image,
    offers: {
      '@type': 'Offer',
      price: product.price,
      priceCurrency: 'RUB',
      availability: product.inStock
        ? 'https://schema.org/InStock'
        : 'https://schema.org/OutOfStock',
    },
  };

  return (
    <>
      <script type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />
      {/* разметка страницы */}
    </>
  );
}

next/image

import Image from 'next/image';

<Image
  src="/hero.jpg"
  alt="Мастерская"
  width={1200}
  height={630}
  priority                       // для картинки первого экрана — грузить сразу
  sizes="(max-width: 768px) 100vw, 50vw"
  placeholder="blur"
  blurDataURL="data:image/jpeg;base64,..."
/>

// Заполнение контейнера
<div className="relative aspect-[4/3]">
  <Image src={product.image} alt="" fill className="object-cover"
         sizes="(max-width: 640px) 100vw, 33vw" />
</div>
// next.config.js — внешние домены нужно разрешать явно
module.exports = {
  images: {
    remotePatterns: [
      { protocol: 'https', hostname: 'cdn.example.ru', pathname: '/images/**' },
    ],
    formats: ['image/avif', 'image/webp'],
  },
};
⚠ Грабли
priority ставьте только на изображение первого экрана (обычно одно — LCP-элемент). Если пометить так десяток картинок, они начнут конкурировать за канал и метрика ухудшится.

Шрифты без скачков макета

// app/layout.tsx
import { Inter } from 'next/font/google';
import localFont from 'next/font/local';

const inter = Inter({
  subsets: ['latin', 'cyrillic'],
  display: 'swap',
  variable: '--font-sans',
});

const brand = localFont({
  src: [{ path: './fonts/Brand-Bold.woff2', weight: '700', style: 'normal' }],
  variable: '--font-brand',
  display: 'swap',
});

export default function RootLayout({ children }) {
  return (
    <html lang="ru" className={`${inter.variable} ${brand.variable}`}>
      <body>{children}</body>
    </html>
  );
}

Файлы шрифтов скачиваются на этапе сборки и раздаются со своего домена: нет запроса к Google, нет мигания текста, автоматически подбирается запасной шрифт с теми же метриками — макет не прыгает.

⚖ Что когда применять
Проверять результат: Lighthouse для метрик, «Просмотр как Googlebot» в Search Console для индексации, opengraph.xyz — для превью ссылки в мессенджерах. Последнее забывают чаще всего, а именно оно видно людям при репосте.

Практика

Задание 1

Настрой полный SEO для страницы товара: динамические метаданные, canonical, Open Graph с генерируемой картинкой, JSON-LD, sitemap и robots.
Решение
// app/layout.tsx — база
import type { Metadata } from 'next';

export const metadata: Metadata = {
  metadataBase: new URL('https://shop.example.ru'),
  title: { default: 'Магазин инструментов', template: '%s — Магазин инструментов' },
  description: 'Профессиональный инструмент с доставкой по России',
  openGraph: { type: 'website', locale: 'ru_RU', siteName: 'Магазин инструментов' },
  twitter: { card: 'summary_large_image' },
  robots: { index: true, follow: true },
};

// app/products/[slug]/page.tsx
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';

export async function generateMetadata({ params }): Promise<Metadata> {
  const { slug } = await params;
  const product = await getProduct(slug);      // дедуплицируется с вызовом в page

  if (!product) return { title: 'Товар не найден', robots: { index: false } };

  const title = `${product.title} — купить за ${product.price} ₽`;
  const description = product.shortDescription.slice(0, 160);

  return {
    title: product.title,
    description,
    alternates: { canonical: `/products/${slug}` },
    openGraph: {
      title,
      description,
      url: `/products/${slug}`,
      type: 'website',
      images: [{ url: product.image, width: 1200, height: 630, alt: product.title }],
    },
    robots: product.isActive
      ? { index: true, follow: true }
      : { index: false, follow: true },       // снятый с продажи не индексируем
  };
}

export default async function ProductPage({ params }) {
  const { slug } = await params;
  const product = await getProduct(slug);
  if (!product) notFound();

  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'Product',
    name: product.title,
    description: product.shortDescription,
    image: [product.image],
    sku: product.sku,
    brand: { '@type': 'Brand', name: product.brand },
    aggregateRating: product.reviewsCount > 0 ? {
      '@type': 'AggregateRating',
      ratingValue: product.rating,
      reviewCount: product.reviewsCount,
    } : undefined,
    offers: {
      '@type': 'Offer',
      url: `https://shop.example.ru/products/${slug}`,
      price: product.price,
      priceCurrency: 'RUB',
      availability: product.inStock
        ? 'https://schema.org/InStock'
        : 'https://schema.org/OutOfStock',
    },
  };

  return (
    <>
      <script type="application/ld+json"
              dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }} />
      <h1>{product.title}</h1>
      {/* ... */}
    </>
  );
}

// app/products/[slug]/opengraph-image.tsx — картинка для соцсетей
import { ImageResponse } from 'next/og';

export const alt = 'Карточка товара';
export const size = { width: 1200, height: 630 };
export const contentType = 'image/png';

export default async function OgImage({ params }) {
  const product = await getProduct(params.slug);

  return new ImageResponse(
    (
      <div style={{
        display: 'flex', width: '100%', height: '100%',
        background: '#14171d', color: '#fff', padding: 64, gap: 48,
        alignItems: 'center',
      }}>
        <img src={product.image} width={400} height={400}
             style={{ objectFit: 'cover', borderRadius: 24 }} />
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div style={{ fontSize: 56, lineHeight: 1.1 }}>{product.title}</div>
          <div style={{ fontSize: 40, color: '#4f8cff' }}>{product.price} ₽</div>
        </div>
      </div>
    ),
    size
  );
}

// app/sitemap.ts
import type { MetadataRoute } from 'next';

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const [products, categories] = await Promise.all([
    db.product.findMany({ where: { isActive: true },
                          select: { slug: true, updatedAt: true } }),
    db.category.findMany({ select: { slug: true, updatedAt: true } }),
  ]);

  const base = 'https://shop.example.ru';

  return [
    { url: base, lastModified: new Date(), changeFrequency: 'daily', priority: 1 },
    ...categories.map(c => ({
      url: `${base}/catalog/${c.slug}`,
      lastModified: c.updatedAt,
      changeFrequency: 'daily' as const,
      priority: 0.9,
    })),
    ...products.map(p => ({
      url: `${base}/products/${p.slug}`,
      lastModified: p.updatedAt,
      changeFrequency: 'weekly' as const,
      priority: 0.7,
    })),
  ];
}

// app/robots.ts
export default function robots(): MetadataRoute.Robots {
  return {
    rules: [
      { userAgent: '*', allow: '/',
        disallow: ['/admin', '/api', '/cart', '/checkout', '/*?utm_'] },
    ],
    sitemap: 'https://shop.example.ru/sitemap.xml',
    host: 'https://shop.example.ru',
  };
}

canonical критичен для магазина: одна и та же карточка доступна по адресам с utm-метками, фильтрами и из разных категорий. Без canonical поисковик считает это дублями и роняет позиции.

Задание 2

Оптимизируй загрузку главной страницы: изображения, шрифты, сторонние скрипты. Объясни, как каждое изменение влияет на Core Web Vitals.
Решение
// app/layout.tsx — шрифты
import { Inter } from 'next/font/google';
import localFont from 'next/font/local';

const inter = Inter({
  subsets: ['latin', 'cyrillic'],
  display: 'swap',
  variable: '--font-sans',
  adjustFontFallback: true,      // подбирает метрики запасного шрифта
});

const brand = localFont({
  src: './fonts/Brand-Bold.woff2',
  weight: '700',
  display: 'swap',
  variable: '--font-brand',
  preload: true,
});

/* Что даёт:
   • файлы скачиваются при сборке и раздаются со своего домена —
     нет обращения к fonts.googleapis.com (минус DNS + TLS + два запроса)
   • подобранный запасной шрифт с теми же метриками — текст
     не «прыгает» при подмене → улучшает CLS
   • display: swap — текст виден сразу запасным шрифтом → лучше FCP */

// app/page.tsx — изображения
import Image from 'next/image';

export default async function HomePage() {
  return (
    <>
      {/* Главное изображение первого экрана — это LCP-элемент */}
      <Image
        src="/hero.jpg"
        alt="Мастерская"
        width={1600} height={900}
        priority                       // без lazy, с высоким приоритетом
        sizes="100vw"
        placeholder="blur"
        blurDataURL="data:image/jpeg;base64,/9j/4AAQ..."
        className="w-full"
      />

      {/* Всё остальное — лениво */}
      <div className="grid grid-cols-[repeat(auto-fit,minmax(240px,1fr))] gap-4">
        {products.map(p => (
          <div key={p.id} className="relative aspect-[4/3]">
            <Image src={p.image} alt={p.title} fill
                   sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 25vw"
                   className="rounded-lg object-cover" />
          </div>
        ))}
      </div>
    </>
  );
}

/* Что даёт:
   • width/height (или fill + aspect-ratio) резервируют место → CLS ≈ 0
   • priority на LCP-картинке → браузер грузит её первой → лучше LCP
   • sizes подсказывает, какой размер скачать → меньше трафика
   • автоматический AVIF/WebP → в 2–4 раза меньше вес
   • lazy для остальных → не конкурируют за канал */

// next.config.js
module.exports = {
  images: {
    remotePatterns: [
      { protocol: 'https', hostname: 'cdn.example.ru', pathname: '/img/**' },
    ],
    formats: ['image/avif', 'image/webp'],
    minimumCacheTTL: 2592000,
  },
  compress: true,
  poweredByHeader: false,
};

// Сторонние скрипты
import Script from 'next/script';

export default function RootLayout({ children }) {
  return (
    <html lang="ru">
      <body>
        {children}

        {/* Аналитика — после того, как страница стала интерактивной */}
        <Script src="https://mc.yandex.ru/metrika/tag.js"
                strategy="afterInteractive" />

        {/* Чат поддержки — в простое, когда браузеру нечем заняться */}
        <Script src="https://widget.example.com/chat.js"
                strategy="lazyOnload" />
      </body>
    </html>
  );
}

/* Стратегии Script:
   beforeInteractive — блокирует, только для критичного (антифрод, полифилы)
   afterInteractive  — по умолчанию, для аналитики
   lazyOnload        — для виджетов, чатов, карт
   worker            — в Web Worker (экспериментально)

   Неправильная стратегия для чата — типовая причина плохого INP:
   виджет весом 200 КБ выполняется, пока пользователь пытается нажать кнопку. */

// Тяжёлые компоненты — динамическим импортом
import dynamic from 'next/dynamic';

const Map = dynamic(() => import('@/components/Map'), {
  ssr: false,
  loading: () => <div className="skeleton aspect-video" />,
});

/* ВЛИЯНИЕ НА МЕТРИКИ
   LCP — priority + AVIF + свой домен шрифтов
   CLS — width/height, aspect-ratio, adjustFontFallback
   INP — lazyOnload для виджетов, dynamic import тяжёлого JS
   FCP — display: swap, серверные компоненты, стриминг

   Проверять: npm run build → Lighthouse → PageSpeed Insights
   на реальном домене (лабораторные данные ≠ полевые). */

Полевые данные (CrUX) важнее лабораторных: Lighthouse на быстром ноутбуке покажет зелёные цифры там, где реальные пользователи со средним телефоном видят совсем другое.