Next.js SEO Optimization

Overview

SEO (Search Engine Optimization) is critical for website visibility. Next.js provides powerful SEO optimization features.

Metadata API

Static Metadata

// app/page.tsx
import { Metadata } from 'next'

export const metadata: Metadata = {
  title: '首页 | 我的网站',
  description: '欢迎来到我的网站',
  keywords: ['Next.js', 'React', 'SEO'],
}

export default function Page() {
  return <h1>首页</h1>
}

Dynamic Metadata

// app/blog/[slug]/page.tsx
export async function generateMetadata({ params }): Promise<Metadata> {
  const post = await getPost(params.slug)
  
  return {
    title: post.title,
    description: post.excerpt,
    openGraph: {
      title: post.title,
      description: post.excerpt,
      images: [post.coverImage],
    },
  }
}

Sitemap

Generating a Sitemap

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

export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const posts = await getPosts()
  
  const postUrls = posts.map((post) => ({
    url: `https://example.com/blog/${post.slug}`,
    lastModified: post.updatedAt,
    changeFrequency: 'weekly' as const,
    priority: 0.8,
  }))
  
  return [
    {
      url: 'https://example.com',
      lastModified: new Date(),
      changeFrequency: 'daily',
      priority: 1,
    },
    {
      url: 'https://example.com/about',
      lastModified: new Date(),
      changeFrequency: 'monthly',
      priority: 0.5,
    },
    ...postUrls,
  ]
}

Robots.txt

// app/robots.ts
import { MetadataRoute } from 'next'

export default function robots(): MetadataRoute.Robots {
  return {
    rules: {
      userAgent: '*',
      allow: '/',
      disallow: '/admin/',
    },
    sitemap: 'https://example.com/sitemap.xml',
  }
}

Structured Data

JSON-LD

export default function BlogPost({ post }) {
  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'Article',
    headline: post.title,
    author: {
      '@type': 'Person',
      name: post.author,
    },
    datePublished: post.publishedAt,
    image: post.coverImage,
  }
  
  return (
    <>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      <article>{post.content}</article>
    </>
  )
}

Best Practices

1. Semantic HTML

<article>
  <header>
    <h1>文章标题</h1>
    <time dateTime="2024-01-01">2024年1月1日</time>
  </header>
  <section>
    <p>文章内容...</p>
  </section>
</article>

2. Image alt Attributes

<Image
  src="/hero.jpg"
  alt="网站首页英雄图 - 展示产品特性"
  width={1200}
  height={600}
/>
<Link href="/blog">
  查看所有博客文章
</Link>

4. Page Load Speed

  • Use the Image component to optimize images
  • Enable code splitting
  • Use a CDN
  • Compress assets

Previous Chapter: Next.js Performance Optimization | Next Chapter: Next.js Security Best Practices