Metadata, SEO, ảnh, font và script
Metadata tĩnh và động, Open Graph image sinh bằng code, sitemap/robots, dữ liệu có cấu trúc JSON-LD, tối ưu ảnh với next/image, font không gây nhảy layout với next/font, và tải script bên thứ ba.
Một lý do lớn để chọn Next.js thay vì SPA là SEO và tốc độ tải. Nhưng những lợi ích đó không tự đến: thiếu metadata, ảnh hero không ưu tiên, font gây nhảy layout, script quảng cáo chặn main thread đều làm mất điểm Core Web Vitals và thứ hạng.
🎯 Mục tiêu học tập
- Khai báo metadata tĩnh và động, kế thừa qua layout
- Sinh OG image động, sitemap, robots
- Thêm JSON-LD cho sản phẩm/bài viết
- Dùng
next/imageđúng: kích thước,sizes, ưu tiên ảnh LCP - Dùng
next/fontvànext/scriptđúng chiến lược
Metadata
// app/layout.tsx
export const metadata: Metadata = {
metadataBase: new URL('https://shop.example.com'),
title: { default: 'Shop', template: '%s | Shop' }, // trang con chỉ cần title: 'Áo thun'
description: 'Cửa hàng thời trang',
openGraph: { type: 'website', locale: 'vi_VN', siteName: 'Shop' },
robots: { index: true, follow: true },
};
// app/products/[slug]/page.tsx
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
const { slug } = await params;
const p = await getProduct(slug); // cache()/use cache: page dùng lại kết quả, không query 2 lần
if (!p) return { title: 'Không tìm thấy' };
return {
title: p.name,
description: p.summary,
alternates: { canonical: `/products/${p.slug}` },
openGraph: { images: [{ url: p.imageUrl, width: 1200, height: 630 }] },
};
}
OG image, sitemap, robots bằng code
// 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 OgImage({ params }: { params: Promise<{ slug: string }> }) {
const p = await getProduct((await params).slug);
return new ImageResponse(
<div style={{ display: 'flex', flexDirection: 'column', width: '100%', height: '100%', padding: 64, background: '#0f172a', color: 'white' }}>
<div style={{ fontSize: 64, fontWeight: 700 }}>{p?.name}</div>
<div style={{ fontSize: 40, marginTop: 24 }}>{p?.price.toLocaleString('vi-VN')} đ</div>
</div>,
size,
);
}
// app/sitemap.ts
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const products = await getAllProductSlugs();
return [
{ url: 'https://shop.example.com', changeFrequency: 'daily', priority: 1 },
...products.map(p => ({ url: `https://shop.example.com/products/${p.slug}`, lastModified: p.updatedAt })),
];
}
// app/robots.ts
export default function robots(): MetadataRoute.Robots {
return { rules: [{ userAgent: '*', allow: '/', disallow: ['/dashboard', '/api'] }], sitemap: 'https://shop.example.com/sitemap.xml' };
}
Sitemap trên 50.000 URL: tách bằng generateSitemaps.
JSON-LD
export default async function ProductPage({ params }: Props) {
const p = await getProduct((await params).slug);
const jsonLd = {
'@context': 'https://schema.org', '@type': 'Product', name: p.name, image: p.imageUrl,
offers: { '@type': 'Offer', priceCurrency: 'VND', price: p.price, availability: p.stock > 0 ? 'https://schema.org/InStock' : 'https://schema.org/OutOfStock' },
};
return (
<>
<script type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd).replace(/</g, '\\u003c') }} /> {/* chặn chèn </script> */}
<ProductView product={p} />
</>
);
}
next/image
import Image from 'next/image';
import hero from './hero.jpg'; // import tĩnh: tự biết width/height + blur placeholder
<Image src={hero} alt="Bộ sưu tập mùa thu" priority placeholder="blur" sizes="100vw" /> {/* ảnh LCP: priority */}
<Image
src={p.imageUrl} alt={p.name}
width={600} height={600} // ảnh từ xa phải có kích thước (hoặc fill) -> không CLS
sizes="(max-width: 768px) 50vw, 25vw" // cho trình duyệt chọn đúng kích thước trong srcset
/>
// next.config.ts — chỉ cho phép domain tin cậy (tránh biến server thành proxy tối ưu ảnh cho bất kỳ ai)
images: { remotePatterns: [new URL('https://cdn.example.com/products/**')], formats: ['image/avif', 'image/webp'] },
- Mặc định lazy load; ảnh trên màn hình đầu tiên (LCP) dùng
priority(hoặcpreload/fetchPriority="high"tuỳ phiên bản). - Thiếu
sizesvới ảnhfill/responsive → trình duyệt tải ảnh quá lớn. - Self-host: tối ưu ảnh tốn CPU — cân nhắc loader của CDN (Cloudinary, imgix) hoặc cache kết quả.
next/font và next/script
// app/layout.tsx
import { Inter, Be_Vietnam_Pro } from 'next/font/google';
const inter = Inter({ subsets: ['latin', 'vietnamese'], display: 'swap', variable: '--font-inter' });
<html lang="vi" className={inter.variable}>…</html>
next/font tải font lúc build và tự host (không gọi Google lúc chạy — tốt cho privacy và tốc độ), tự tính
size-adjust cho font dự phòng nên gần như không còn CLS khi font tải xong.
import Script from 'next/script';
<Script src="https://www.googletagmanager.com/gtag/js?id=G-XXX" strategy="afterInteractive" />
<Script src="https://widget.chat.com/w.js" strategy="lazyOnload" /> {/* chat widget: tải khi rảnh */}
| strategy | Khi nào tải |
|---|---|
beforeInteractive | Trước hydration — chỉ cho script thật sự bắt buộc (consent manager) |
afterInteractive | Sau hydration (mặc định) — analytics |
lazyOnload | Khi trình duyệt rảnh — chat, social widget |
🚩 Sai lầm hay gặp
- Mọi trang cùng một title/description.
- Ảnh hero lazy load (LCP chậm).
remotePatternscho phép mọi domain.- Chèn JSON-LD bằng
JSON.stringifykhông escape<.
🏋️ Bài tập thực hành
Thêm metadata động, canonical, OG image sinh bằng code, JSON-LD Product, sitemap, robots. Kiểm tra bằng Rich Results Test và Lighthouse SEO = 100. Tối ưu ảnh/font để LCP < 2.5s, CLS < 0.1 trên mobile.
📚 Tài nguyên học tập
-
Next.js — Metadata and OG imagesHướng dẫnDocs
-
Next.js — Image Optimizationnext/imageDocs
-
Google Search CentralSEO chính thứcDocs
✅ Tự đánh giá hoàn thành
- Tôi viết được
generateMetadatakhông query trùng - Tôi sinh được OG image, sitemap, robots
- Tôi dùng
next/imagevớisizesvàpriorityđúng - Tôi chọn đúng strategy cho script bên thứ ba