这是用户在 2024-7-21 11:14 为 https://dminhvu.com/post/nextjs-seo 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?
Schedule time with me 与我安排时间

Next.js SEO: The Complete Checklist to Boost Your Site Ranking
Next.js SEO:提升网站排名的完整清单

Minh Vu

By Minh Vu 作者:Minh Vu

Updated Mar 01, 2024 更新日期:2024 年 3 月 1 日

8.5K reads 8.5K 阅读量

Figure: Next.js SEO: The Complete Checklist to Boost Your Site Ranking

Disclaimer: All content on this website is derived directly from my own expertise and experiences. No AI-generated text or automated content creation tools are used.
免责声明:本网站上的所有内容均直接源自我个人的专业知识和经验。未使用任何人工智能生成的文本或自动化内容创作工具。

SEO (Search Engine Optimization) is one of the key factors to rank your website higher on Google and receive more traffic.
SEO(搜索引擎优化)是使您的网站在谷歌上排名更高并获得更多流量的关键因素之一。

In this tutorial, I will show you what I have done to optimize this blog for SEO by providing a checklist that you can follow easily.
在这个教程中,我将向您展示我为优化这个博客的搜索引擎优化所做的工作,提供一个您可以轻松遵循的清单。

I have spent a lot of time researching and learning about SEO, especially for Next.js, and found some optimal ways to do it. So I hope this tutorial will help you save time and effort.
我花了很多时间研究和学习 SEO,特别是针对 Next.js 的 SEO,并找到了一些最优的方法来实现它。所以我希望这个教程能帮助你节省时间和精力。

I will put the items covered in this tutorial inside the Table of Contents below. You can click on any item to jump to the section.
我将把本教程涵盖的内容放在下面的目录中。您可以点击任何项目跳转到相应部分。

Please note that some parts are different for Next.js Pages Router and Next.js App Router, I will mention it in the tutorial. Otherwise, it can be applied to both.
请注意,Next.js Pages Router 和 Next.js App Router 的某些部分是不同的,我会在教程中提及。否则,它适用于两者。

Contents 目录

Meta Tags 元标签

Meta tags provide information about your website to search engines and social media platforms.
Meta 标签为搜索引擎和社交媒体平台提供有关您网站的信息。

Your website should include the following standard meta tags:
您的网站应包含以下标准元标签:

  • title 标题
  • description 描述
  • keywords 关键词
  • robots 机器人
  • viewport 视口
  • charSet 字符集

Open Graph meta tags: 开放图谱元标签:

  • og:site_name
  • og:locale
  • og:title og:标题
  • og:description og:描述
  • og:type
  • og:url
  • og:image
  • og:image:alt
  • og:image:type
  • og:image:width
  • og:image:height

Article meta tags (actually it's also OpenGraph):
文章元标签(实际上也是开放图谱协议):

  • article:published_time
  • article:modified_time
  • article:author 文章:作者

Twitter meta tags: Twitter 元标签:

  • twitter:card
  • twitter:site
  • twitter:creator twitter:创作者
  • twitter:title twitter:标题
  • twitter:description twitter:描述
  • twitter:image

Please note that for the og:image and twitter:image tags, you should use the PNG or JPG format as some social media platforms will not read the WebP format.
请注意,对于 og:imagetwitter:image 标签,您应使用 PNG 或 JPG 格式,因为某些社交媒体平台无法读取 WebP 格式。

Meta Tags for Next.js Pages Router
Next.js 页面路由器的元标签

For example, the current page has the following meta tags when I use Next.js Pages Router:
例如,当我使用 Next.js Pages Router 时,当前页面有以下 meta 标签:

pages/[slug].tsx
import Head from "next/head";
 
export default function Page() {
  return (
    <Head>
      <title>
        Next.js SEO: The Complete Checklist to Boost Your Site Ranking
      </title>
      <meta
        name="description"
        content="Learn how to optimize your Next.js website for SEO by following this complete checklist."
      />
      <meta
        name="keywords"
        content="nextjs seo complete checklist, nextjs seo tutorial"
      />
      <meta name="robots" content="index, follow" />
      <meta name="googlebot" content="index, follow" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <meta charSet="utf-8" />
      <meta property="og:site_name" content="Blog | Minh Vu" />
      <meta property="og:locale" content="en_US" />
      <meta
        property="og:title"
        content="Next.js SEO: The Complete Checklist to Boost Your Site Ranking"
      />
      <meta
        property="og:description"
        content="Learn how to optimize your Next.js website for SEO by following this complete checklist."
      />
      <meta property="og:type" content="website" />
      <meta property="og:url" content="https://dminhvu.com/nextjs-seo" />
      <meta
        property="og:image"
        content="https://ik.imagekit.io/dminhvu/assets/nextjs-seo/thumbnail.png?tr=f-png"
      />
      <meta property="og:image:alt" content="Next.js SEO" />
      <meta property="og:image:type" content="image/png" />
      <meta property="og:image:width" content="1200" />
      <meta property="og:image:height" content="630" />
      <meta
        property="article:published_time"
        content="2024-01-11T11:35:00+07:00"
      />
      <meta
        property="article:modified_time"
        content="2024-01-11T11:35:00+07:00"
      />
      <meta
        property="article:author"
        content="https://www.linkedin.com/in/dminhvu02"
      />
      <meta name="twitter:card" content="summary_large_image" />
      <meta name="twitter:site" content="@dminhvu02" />
      <meta name="twitter:creator" content="@dminhvu02" />
      <meta
        name="twitter:title"
        content="Next.js SEO: The Complete Checklist to Boost Your Site Ranking"
      />
      <meta
        name="twitter:description"
        content="Learn how to optimize your Next.js website for SEO by following this complete checklist."
      />
      <meta
        name="twitter:image"
        content="https://ik.imagekit.io/dminhvu/assets/nextjs-seo/thumbnail.png?tr=f-png"
      />
    </Head>
  );
}

Meta Tags for Next.js App Router
Next.js App Router 的 Meta 标签

For Next.js App Router, it's even easier to define those tags by using the built-in export const metadata argument for static metadata, and the generateMetadata function for pages that have dynamic data (blog posts, products, etc.).
对于 Next.js 的 App Router,定义这些标签更加简单。可以使用内置的 export const metadata 参数来定义静态元数据,对于包含动态数据(博客文章、产品等)的页面,可以使用 generateMetadata 函数。

Let's find out how to do it. You can visit the metadata docs to learn more.
让我们来了解如何做到这一点。您可以访问元数据文档以了解更多信息。

Static Metadata 静态元数据

You can define static metadata by adding the export const metadata argument inside page.tsx or layout.tsx:
您可以通过在 export const metadatalayout.tsx 内添加 page.tsx 参数来定义静态元数据:

app/layout.tsx
import type { Viewport, Metadata } from "next";
 
export const viewport: Viewport = {
  width: "device-width",
  initialScale: 1,
  themeColor: "#ffffff"
};
 
export const metadata: Metadata = {
  metadataBase: new URL("https://dminhvu.com"),
  openGraph: {
    siteName: "Blog | Minh Vu",
    type: "website",
    locale: "en_US"
  },
  robots: {
    index: true,
    follow: true,
    "max-image-preview": "large",
    "max-snippet": -1,
    "max-video-preview": -1,
    googleBot: "index, follow"
  },
  alternates: {
    types: {
      "application/rss+xml": "https://dminhvu.com/rss.xml"
    }
  },
  applicationName: "Blog | Minh Vu",
  appleWebApp: {
    title: "Blog | Minh Vu",
    statusBarStyle: "default",
    capable: true
  },
  verification: {
    google: "YOUR_DATA",
    yandex: ["YOUR_DATA"],
    other: {
      "msvalidate.01": ["YOUR_DATA"],
      "facebook-domain-verification": ["YOUR_DATA"]
    }
  },
  icons: {
    icon: [
      {
        url: "/favicon.ico",
        type: "image/x-icon"
      },
      {
        url: "/favicon-16x16.png",
        sizes: "16x16",
        type: "image/png"
      }
      // add favicon-32x32.png, favicon-96x96.png, android-chrome-192x192.png
    ],
    shortcut: [
      {
        url: "/favicon.ico",
        type: "image/x-icon"
      }
    ],
    apple: [
      {
        url: "/apple-icon-57x57.png",
        sizes: "57x57",
        type: "image/png"
      },
      {
        url: "/apple-icon-60x60.png",
        sizes: "60x60",
        type: "image/png"
      }
      // add apple-icon-72x72.png, apple-icon-76x76.png, apple-icon-114x114.png, apple-icon-120x120.png, apple-icon-144x144.png, apple-icon-152x152.png, apple-icon-180x180.png
    ]
  }
};
app/page.tsx
import { Metadata } from "next";
 
export const metadata: Metadata = {
  title: "Elastic Stack, Next.js, Python, JavaScript Tutorials | dminhvu",
  description:
    "dminhvu.com - Programming blog for everyone to learn Elastic Stack, Next.js, Python, JavaScript, React, Machine Learning, Data Science, and more.",
  keywords: [
    "elastic",
    "python",
    "javascript",
    "react",
    "machine learning",
    "data science"
  ],
  openGraph: {
    url: "https://dminhvu.com",
    type: "website",
    title: "Elastic Stack, Next.js, Python, JavaScript Tutorials | dminhvu",
    description:
      "dminhvu.com - Programming blog for everyone to learn Elastic Stack, Next.js, Python, JavaScript, React, Machine Learning, Data Science, and more.",
    images: [
      {
        url: "https://dminhvu.com/images/home/thumbnail.png",
        width: 1200,
        height: 630,
        alt: "dminhvu"
      }
    ]
  },
  twitter: {
    card: "summary_large_image",
    title: "Elastic Stack, Next.js, Python, JavaScript Tutorials | dminhvu",
    description:
      "dminhvu.com - Programming blog for everyone to learn Elastic Stack, Next.js, Python, JavaScript, React, Machine Learning, Data Science, and more.",
    creator: "@dminhvu02",
    site: "@dminhvu02",
    images: [
      {
        url: "https://dminhvu.com/images/home/thumbnail.png",
        width: 1200,
        height: 630,
        alt: "dminhvu"
      }
    ]
  },
  alternates: {
    canonical: "https://dminhvu.com"
  }
};

Dynamic Metadata 动态元数据

Dynamic metadata can be defined by using the generateMetadata function, this is useful when you have dynamic pages like [slug]/page.tsx, or [id]/page.tsx:
动态元数据可以通过使用 generateMetadata 函数来定义,这在您有像 [slug]/page.tsx[id]/page.tsx 这样的动态页面时非常有用:

app/[slug]/page.tsx
import type { Metadata, ResolvingMetadata } from "next";
 
type Params = {
  slug: string;
};
 
type Props = {
  params: Params;
  searchParams: { [key: string]: string | string[] | undefined };
};
 
export async function generateMetadata(
  { params, searchParams }: Props,
  parent: ResolvingMetadata
): Promise<Metadata> {
  const { slug } = params;
 
  const post: Post = await fetch(`YOUR_ENDPOINT`, {
    method: "GET",
    next: {
      revalidate: 60 * 60 * 24
    }
  }).then((res) => res.json());
 
  return {
    title: `${post.title} | dminhvu`,
    authors: [
      {
        name: post.author || "Minh Vu"
      }
    ],
    description: post.description,
    keywords: post.keywords,
    openGraph: {
      title: `${post.title} | dminhvu`,
      description: post.description,
      type: "article",
      url: `https://dminhvu.com/${post.slug}`,
      publishedTime: post.created_at,
      modifiedTime: post.modified_at,
      authors: ["https://dminhvu.com/about"],
      tags: post.categories,
      images: [
        {
          url: `https://ik.imagekit.io/dminhvu/assets/${post.slug}/thumbnail.png?tr=f-png`,
          width: 1024,
          height: 576,
          alt: post.title,
          type: "image/png"
        }
      ]
    },
    twitter: {
      card: "summary_large_image",
      site: "@dminhvu02",
      creator: "@dminhvu02",
      title: `${post.title} | dminhvu`,
      description: post.description,
      images: [
        {
          url: `https://ik.imagekit.io/dminhvu/assets/${post.slug}/thumbnail.png?tr=f-png`,
          width: 1024,
          height: 576,
          alt: post.title
        }
      ]
    },
    alternates: {
      canonical: `https://dminhvu.com/${post.slug}`
    }
  };
}

Please note that the charSet and viewport are automatically added by Next.js App Router, so you don't need to define them.
请注意, charSetviewport 是由 Next.js App Router 自动添加的,因此您无需定义它们。

JSON-LD Schema JSON-LD 架构

This part can be applied to both Pages Router and App Router.
这个部分适用于 Pages Router 和 App Router。

I have written an in-depth post about How to Add JSON-LD Schema to Your Next.js Website that you can read to dive deeper into this topic.
我写了一篇深入探讨如何在 Next.js 网站中添加 JSON-LD 架构的文章,你可以阅读它以更深入地了解这个主题。

JSON-LD is a lightweight Linked Data format. It is easy for machines to parse and generate. It is currently one of the most widely used formats for Linked Data.
JSON-LD 是一种轻量级的链接数据格式。它易于机器解析和生成。目前,它是最广泛使用的链接数据格式之一。

You can easily generate JSON-LD Schema for your website by using the Schema Markup Generator Tool.
您可以使用 Schema 标记生成器工具轻松为您的网站生成 JSON-LD Schema。

For example, the current page has the following JSON-LD Schema:
例如,当前页面具有以下 JSON-LD Schema:

const jsonLd = {
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  mainEntityOfPage: {
    "@type": "WebPage",
    "@id": "https://dminhvu.com/nextjs-seo"
  },
  headline: "Next.js SEO: The Complete Checklist to Boost Your Site Ranking",
  description:
    "Learn how to optimize your Next.js website for SEO by following this complete checklist.",
  image:
    "https://ik.imagekit.io/dminhvu/assets/nextjs-seo/thumbnail.png?tr=f-png",
  dateCreated: "2024-01-11T11:35:00+07:00",
  datePublished: "2024-01-11T11:35:00+07:00",
  dateModified: "2024-01-11T11:35:00+07:00",
  author: {
    "@type": "Person",
    name: "Minh Vu",
    url: "https://www.linkedin.com/in/dminhvu02"
  },
  publisher: {
    "@type": "Person",
    name: "Minh Vu",
    logo: {
      "@type": "ImageObject",
      url: "https://dminhvu.com/avatar_zoom.jpg"
    }
  },
  inLanguage: "en-US",
  isFamilyFriendly: "true"
};

And I can put it anywhere, whether inside the head tag or the body tag is fine:
我可以把它放在任何地方,无论是在 head 标签内还是 body 标签内都可以:

import Head from "next/head";
 
export default function Page() {
  return (
    <div>
      {/* other parts */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
    </div>
  );
}

Sitemap 网站地图

Your website should provide a sitemap so that search engines can easily crawl and index your pages.
您的网站应该提供一个网站地图,以便搜索引擎可以轻松地爬取和索引您的页面。

Generate Sitemap for Next.js Pages Router
为 Next.js 页面路由生成网站地图

For Next.js Pages Router, you can use next-sitemap to generate a sitemap for your Next.js website after building.
对于 Next.js 页面路由,您可以在构建后使用 next-sitemap 为您的 Next.js 网站生成网站地图。

For example, running the following command will install next-sitemap and generate a sitemap for this blog:
例如,运行以下命令将安装 next-sitemap 并为此博客生成网站地图:

npm install next-sitemap
npx next-sitemap

A sitemap will be generated at public/sitemap.xml:
将在 public/sitemap.xml 生成网站地图:

public/sitemap.xml
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9" xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:mobile="http://www.google.com/schemas/sitemap-mobile/1.0" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1">
<url>
  <loc>https://dminhvu.com</loc>
    <lastmod>2024-01-11T02:03:09.613Z</lastmod>
    <changefreq>daily</changefreq>
  <priority>0.7</priority>
</url>
<!-- other pages -->
</urlset>

Please visit the next-sitemap page for more information.
请访问 next-sitemap 页面以获取更多信息。

Generate Sitemap for Next.js App Router
为 Next.js 应用路由器生成网站地图

For Next.js App Router, you can define the sitemap.ts file at app/sitemap.ts:
对于 Next.js App Router,您可以在 sitemap.ts 文件中定义 app/sitemap.ts

app/sitemap.ts
import {
  getAllCategories,
  getAllPostSlugsWithModifyTime
} from "@/utils/getData";
import { MetadataRoute } from "next";
 
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
  const defaultPages = [
    {
      url: "https://dminhvu.com",
      lastModified: new Date(),
      changeFrequency: "daily",
      priority: 1
    },
    {
      url: "https://dminhvu.com/about",
      lastModified: new Date(),
      changeFrequency: "monthly",
      priority: 0.9
    },
    {
      url: "https://dminhvu.com/contact",
      lastModified: new Date(),
      changeFrequency: "monthly",
      priority: 0.9
    }
    // other pages
  ];
 
  const postSlugs = await getAllPostSlugsWithModifyTime();
  const categorySlugs = await getAllCategories();
 
  const sitemap = [
    ...defaultPages,
    ...postSlugs.map((e: any) => ({
      url: `https://dminhvu.com/${e.slug}`,
      lastModified: e.modified_at,
      changeFrequency: "daily",
      priority: 0.8
    })),
    ...categorySlugs.map((e: any) => ({
      url: `https://dminhvu.com/category/${e}`,
      lastModified: new Date(),
      changeFrequency: "daily",
      priority: 0.7
    }))
  ];
 
  return sitemap;
}

With this sitemap.ts file created, you can access the sitemap at https://dminhvu.com/sitemap.xml.
创建了这个 sitemap.ts 文件后,您可以在 https://dminhvu.com/sitemap.xml 访问网站地图。

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://dminhvu.com</loc>
    <lastmod>2024-01-11T02:03:09.613Z</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.7</priority>
  </url>
  <!-- other pages -->
</urlset>

Visit Next.js App Router Sitemap to learn more.
访问 Next.js 应用路由器站点地图了解更多信息。

robots.txt

A robots.txt file should be added to tell search engines which pages to crawl and which pages to ignore.
应添加一个 robots.txt 文件来告诉搜索引擎哪些页面需要爬取,哪些页面需要忽略。

robots.txt for Next.js Pages Router
Next.js Pages Router 的 robots.txt

For Next.js Pages Router, you can create a robots.txt file at public/robots.txt:
对于 Next.js 的 Pages Router,你可以在 public/robots.txt 创建一个 robots.txt 文件:

public/robots.txt
User-agent: *
Disallow:
Sitemap: https://dminhvu.com/sitemap.xml

You can prevent the search engine from crawling a page (usually search result pages, noindex pages, etc.) by adding the following line:
您可以通过添加以下行来阻止搜索引擎抓取页面(通常是搜索结果页面、noindex 页面等):

public/robots.txt
User-agent: *
Disallow: /search?q=
Disallow: /admin

robots.txt for Next.js App Router
Next.js 应用路由器的 robots.txt

For Next.js App Router, you don't need to manually define a robots.txt file. Instead, you can define the robots.ts file at app/robots.ts:
对于 Next.js 的 App Router,你不需要手动定义一个 robots.txt 文件。相反,你可以在 app/robots.ts 定义 robots.ts 文件:

app/robots.ts
import { MetadataRoute } from "next";
 
export default function robots(): MetadataRoute.Robots {
  return {
    rules: {
      userAgent: "*",
      allow: ["/"],
      disallow: ["/search?q=", "/admin/"]
    },
    sitemap: ["https://dminhvu.com/sitemap.xml"]
  };
}

With this robots.ts file created, you can access the robots.txt file at https://dminhvu.com/robots.txt.
创建了这个 robots.ts 文件后,你可以在 https://dminhvu.com/robots.txt 访问 robots.txt 文件。

User-agent: *
Allow: /
Disallow: /search?q=
Disallow: /admin
 
Sitemap: https://dminhvu.com/sitemap.xml

There are some important link tags like the meta tags that you should include on your website:
有一些重要的 link 标签,比如 meta 标签,你应该在你的网站上包含:

  • canonical 规范的
  • alternate 备用
  • icon 图标
  • apple-touch-icon
  • manifest 清单

For example, the current page has the following link tags if I use the Pages Router:
例如,如果我使用 Pages Router,当前页面有以下 link 标签:

pages/_app.tsx
import Head from "next/head";
 
export default function Page() {
  return (
    <Head>
      {/* other parts */}
      <link
        rel="alternate"
        type="application/rss+xml"
        href="https://dminhvu.com/rss.xml"
      />
      <link rel="icon" href="/favicon.ico" type="image/x-icon" />
      <link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png" />
      <link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png" />
      {/* add apple-touch-icon-72x72.png, apple-touch-icon-76x76.png, apple-touch-icon-114x114.png, apple-touch-icon-120x120.png, apple-touch-icon-144x144.png, apple-touch-icon-152x152.png, apple-touch-icon-180x180.png */}
      <link
        rel="icon"
        type="image/png"
        href="/favicon-16x16.png"
        sizes="16x16"
      />
      {/* add favicon-32x32.png, favicon-96x96.png, android-chrome-192x192.png */}
    </Head>
  );
}
pages/[slug].tsx
import Head from "next/head";
 
export default function Page() {
  return (
    <Head>
      {/* other parts */}
      <link rel="canonical" href="https://dminhvu.com/nextjs-seo" />
    </Head>
  );
}

For Next.js App Router, the link tags can be defined using the export const metadata or generateMetadata similar to the meta tags section.
对于 Next.js App Router,链接标签可以使用 export const metadatagenerateMetadata 来定义,类似于元标签部分。

The code below is exactly the same as the meta tags for Next.js App Router section above.
下面的代码与上面 Next.js App Router 部分的 meta 标签完全相同。

app/layout.tsx
export const metadata: Metadata = {
  // other parts
  alternates: {
    types: {
      "application/rss+xml": "https://dminhvu.com/rss.xml"
    }
  },
  icons: {
    icon: [
      {
        url: "/favicon.ico",
        type: "image/x-icon"
      },
      {
        url: "/favicon-16x16.png",
        sizes: "16x16",
        type: "image/png"
      }
      // add favicon-32x32.png, favicon-96x96.png, android-chrome-192x192.png
    ],
    shortcut: [
      {
        url: "/favicon.ico",
        type: "image/x-icon"
      }
    ],
    apple: [
      {
        url: "/apple-icon-57x57.png",
        sizes: "57x57",
        type: "image/png"
      },
      {
        url: "/apple-icon-60x60.png",
        sizes: "60x60",
        type: "image/png"
      }
      // add apple-icon-72x72.png, apple-icon-76x76.png, apple-icon-114x114.png, apple-icon-120x120.png, apple-icon-144x144.png, apple-icon-152x152.png, apple-icon-180x180.png
    ]
  }
};
app/page.tsx
export const metadata: Metadata = {
  // other parts
  alternates: {
    canonical: "https://dminhvu.com"
  }
};

Script Optimization 脚本优化

Script Optimization for General Scripts
通用脚本的脚本优化

Next.js provides a built-in component called <Script> to add external scripts to your website.
Next.js 提供了一个内置组件 <Script> ,用于在您的网站中添加外部脚本。

For example, you can add Google Analytics to your website by adding the following script tag:
例如,您可以通过添加以下脚本标签将 Google Analytics 添加到您的网站:

pages/_app.tsx
import Head from "next/head";
import Script from "next/script";
 
export default function Page() {
  return (
    <Head>
      {/* other parts */}
      {process.env.NODE_ENV === "production" && (
        <>
          <Script async strategy="afterInteractive" id="analytics">
            {`
              window.dataLayer = window.dataLayer || [];
              function gtag(){dataLayer.push(arguments);}
              gtag('js', new Date());
              gtag('config', 'G-XXXXXXXXXX');
            `}
          </Script>
        </>
      )}
    </Head>
  );
}

Script Optimization for Common Third-Party Integrations
常见第三方集成的脚本优化

Next.js App Router introduces a new library called @next/third-parties for:
Next.js App Router 引入了一个名为@next/third-parties 的新库,用于:

To use the @next/third-parties library, you need to install it:
要使用 @next/third-parties 库,你需要安装它:

npm install @next/third-parties

Then, you can add the following code to your app/layout.tsx:
然后,您可以将以下代码添加到您的 app/layout.tsx 中:

app/layout.tsx
import { GoogleTagManager } from "@next/third-parties/google";
import { GoogleAnalytics } from "@next/third-parties/google";
import Head from "next/head";
 
export default function Page() {
  return (
    <html lang="en" className="scroll-smooth" suppressHydrationWarning>
      {process.env.NODE_ENV === "production" && (
        <>
          <GoogleAnalytics gaId="G-XXXXXXXXXX" />
          {/* other scripts */}
        </>
      )}
      {/* other parts */}
    </html>
  );
}

Please note that you don't need to include both GoogleTagManager and GoogleAnalytics if you only use one of them.
请注意,如果您只使用其中一个,则无需同时包含 GoogleTagManager 和 GoogleAnalytics。

Image Optimization 图像优化

This part can be applied to both Pages Router and App Router.
这部分既适用于 Pages Router 也适用于 App Router。

Image optimization is also an important part of SEO as it helps your website load faster.
图像优化也是搜索引擎优化的重要组成部分,因为它有助于提高网站的加载速度。

Faster image rendering speed will contribute to the Google PageSpeed score, which can improve user experience and SEO.
更快的图像渲染速度将有助于提高 Google PageSpeed 分数,这可以改善用户体验和搜索引擎优化。

You can use next/image to optimize images in your Next.js website.
你可以使用 next/image 来优化 Next.js 网站中的图片。

For example, the following code will optimize this post thumbnail:
例如,以下代码将优化这个文章缩略图:

import Image from "next/image";
 
export default function Page() {
  return (
    <Image
      src="https://ik.imagekit.io/dminhvu/assets/nextjs-seo/thumbnail.png?tr=f-webp"
      alt="Next.js SEO"
      width={1200}
      height={630}
    />
  );
}

Remember to use a CDN to serve your media (images, videos, etc.) to improve the loading speed. Here I used ImageKit to serve my images. Some people prefer Cloudinary or Vercel built-in image optimization.
请记住使用 CDN 来提供您的媒体(图片、视频等),以提高加载速度。这里我使用了 ImageKit 来提供我的图片。有些人更喜欢 Cloudinary 或 Vercel 内置的图像优化。

You can also use DigitalOcean Spaces to store your media files. Use this link to get $200 free credit for 60 days to try it out.
您还可以使用 DigitalOcean Spaces 来存储您的媒体文件。使用此链接可获得 60 天$200 免费信用来试用。

For the image format, I prefer to use WebP because it has a smaller size than PNG and JPEG.
对于图像格式,我更喜欢使用 WebP,因为它比 PNG 和 JPEG 的文件大小更小。

Conclusion 结论

I hope this tutorial will help you optimize your Next.js website for SEO.
我希望本教程能帮助你优化你的 Next.js 网站以提高搜索引擎优化。

In general, there are several important points that you should pay attention to:
总的来说,你应该注意以下几个重要方面:

  • Meta tags 元标签
  • JSON-LD Schema JSON-LD 模式
  • Sitemap 网站地图
  • robots.txt
  • Link tags 链接标签
  • Script optimization 脚本优化
  • Image optimization 图像优化

If you have any questions, please leave a comment below.
如果您有任何问题,请在下方留言。

Minh Vu

Minh Vu

Software Engineer 软件工程师

Hi guys 👋, I'm a developer specializing in Elastic Stack and Next.js. My blog shares practical tutorials and insights based on 3+ years of hands-on experience. Open to freelance opportunities — let's get in touch!
大家好 👋,我是一名专门研究 Elastic Stack 和 Next.js 的开发者。我的博客分享了基于 3 年多实践经验的实用教程和见解。欢迎自由职业机会 — 让我们联系吧!

Comments 评论

Minh Vu

Feb 22, 2024 2024 年 2 月 22 日

I just added the robots.txt section for Next.js App Router. Cheers!
我刚刚为 Next.js App Router 添加了 robots.txt 部分。干杯!

kiwi 猕猴桃

Feb 25, 2024 2024 年 2 月 25 日

Thanks for the in-depth tutorial, can you elaborate more about JSON LD?
感谢这篇深入的教程,你能详细说明一下 JSON-LD 吗?

jayden 杰登

Feb 28, 2024 2024 年 2 月 28 日

thorough and detailed explanation
详尽而全面的解释

Rowland Ricketts 罗兰·里基茨

Mar 05, 2024 2024 年 3 月 5 日

Thanks for sharing this,  感谢你分享这个,

kunkka 昆卡

May 27, 2024 2024 年 5 月 27 日

Thanks for sharing, good article
感谢分享,好文章

David 大卫

Jul 14, 2024 2024 年 7 月 14 日

Indeed, this tutorial will really save me a lot of time and effort. Cheers, man!
的确,这个教程真的会为我节省很多时间和精力。谢谢你,兄弟!

David 大卫

Jul 14, 2024 2024 年 7 月 14 日

Indeed, this tutorial will really save me a lot of time and effort. Cheers, man!
确实,这个教程真的会为我节省很多时间和精力。谢谢你,伙计!

Leave a Comment 发表评论

Receive Latest Updates 📬
接收最新更新 📬

Get every new post, special offers, and more via email. No fee required.
通过电子邮件获取每一篇新帖子、特别优惠和更多内容。无需费用。