Простой и легкий плагин SEO для приложений Next.js.
Хотя next-head-seo поддерживает только важные свойства SEO, этого было бы достаточно для большинства веб-сайтов.
Если вам нужны расширенные настройки SEO, такие как структурированные данные, вместо этого используйте Next-SEO.
$ npm install next-head-seo
# or with yarn
$ yarn add next-head-seo Импортируйте next-head-seo на каждом компоненте страницы и добавьте желаемые свойства.
Пример:
// pages/example.tsx
import NextHeadSeo from 'next-head-seo' ;
const Page = ( ) => (
< >
< h1 > Hello! </ h1 >
< NextHeadSeo
title = "Hello!"
description = "Some description"
canonical = "https://example.com/hello"
og = { {
title : "Open graph title" ,
image : "https://example.com/og.png" ,
} }
/>
</ >
) ;
export default Page
// Output:
// <head>
// <title>Hello!</title>
// <meta name="description" content="Some description" />
// <link rel="canonical" href="https://example.com/hello"/>
// <meta property="og:title" content="Open graph title"/>
// <meta property="og:image" content="https://example.com/og.png"/>
// </head> Есть 2 параметра для настройки SEO -Problies Default SEO.
<NextHeadSeo /> on _app.tsx Первый вариант - разместить <NextHeadSeo /> со значениями по умолчанию на _app.tsx .
// pages/_app.tsx
import type { AppProps } from 'next/app'
import NextHeadSeo from 'next-head-seo' ;
function MyApp ( { Component , pageProps } : AppProps ) {
return (
< >
{ /* Default SEO configuration */ }
< NextHeadSeo
og = { {
image : "https://example.com/default-og.png" ,
type : 'article' ,
siteName : 'Your app name' ,
} }
twitter = { {
card : "summary"
} }
/>
{ /* Place <Component /> after <NextHeadSeo /> */ }
< Component { ... pageProps } />
</ >
) ;
}
export default MyApp Убедитесь, что <NextHeadSeo /> размещается до <Component {...pageProps} /> поскольку следующая головка Seo уважает последнее значение для того же имени свойства.
В качестве альтернативы, просто создайте компонент обертки, который можно использовать на каждом компоненте страницы. Это более гибкий и надежный способ установить значения по умолчанию.
Вот пример компонента обертки:
// components/MyPageSeo.tsx
import NextHeadSeo from 'next-head-seo' ;
// types
export type MyPageSeoProps = {
path : string ;
title ?: string ;
description ?: string ;
ogImagePath ?: string ;
noindex ?: boolean ;
noTitleTemplate ?: boolean ;
} ;
export const MyPageSeo : React . FC < MyPageSeoProps > = ( props ) => {
const {
path ,
title = "Default title" ,
description = "Default description" ,
ogImagePath = "/default-og.png" ,
noindex ,
noTitleTemplate ,
} = props ;
// Set APP_ROOT_URL on enviroment variables
// e.g. APP_ROOT_URL=https://example.com
// https://nextjs.org/docs/basic-features/environment-variables
const APP_ROOT_URL = process . env . NEXT_PUBLIC_APP_ROOT_URL ;
// Absolute page url
const pageUrl = APP_ROOT_URL + path
// Absolute og image url
const ogImageUrl = APP_ROOT_URL + ogImagePath
return (
< NextHeadSeo
title = { noTitleTemplate ? title : ` ${ title } - MyAppName` }
canonical = { pageUrl }
description = { description }
robots = { noindex ? 'noindex, nofollow' : undefined }
og = { {
title ,
description ,
url : pageUrl ,
image : ogImageUrl ,
type : 'article' ,
siteName : 'MyAppName' ,
} }
twitter = { {
card : "summary_large_image" ,
} }
/>
) ;
} ; Затем поместите <MyPageSeo /> в каждой компоненте страницы.
// pages/example.tsx
import { MyPageSeo } from "../components/MyPageSeo"
const Page = ( ) => (
< >
< h1 > Hello! </ h1 >
< MyPageSeo
path = "/example"
title = "Hello!"
noindex = { true }
/>
</ >
) ;
export default Page
// Output:
// <head>
// <title>Hello! - MyAppName</title>
// <meta name="robots" content="noindex, nofollow"/>
// <meta name="description" content="Default description" />
// <link rel="canonical" href="https://example.com/example"/>
// <meta property="og:url" content="https://example.com/example"/>
// <meta property="og:title" content="Hello!"/>
// <meta property="og:description" content="Default description"/>
// <meta property="og:image" content="https://example.com//default-og.png"/>
// <meta property="og:type" content="article"/>
// <meta property="og:site_name" content="MyAppName"/>
// <meta name="twitter:card" content="summary_large_image"/>
// </head> Все реквизиты для next-head-seo являются необязательными.
| Проп | Описание | Тип |
|---|---|---|
| заголовок | ✅ Рекомендуется установить на всех страницах. Название страницы. | нить |
| канонический | ✅ Рекомендуется установить на всех страницах. Канонический URL страницы. | нить |
| роботы | Установите noindex, nofollow только тогда, когда вы не хотите, чтобы страница была проиндексирована в поисковых системах. В противном случае вам не нужно использовать эту опору. | "noindex, nofollow""index, follow""noindex""nofollow" |
| описание | ✅ Рекомендуется установить на всех страницах. Описание страницы. Текст после 150 символов будет усечен, как и Google. | нить |
| Twitter.card | Тип изображения карты Twitter. Установить вместе с og:image .Смотрите подробную информацию: карты Twitter | "summary""summary_large_image""player""app" |
| Twitter.site | Имя пользователя Twitter Начиная с @ | нить |
| Og.title | Для OG: заголовок. Автоматически используйте значение title , если пусто.Смотрите подробную информацию: протокол открытого графика | нить |
| OG.Description | Для OG: описание. Автоматически используйте значение description , если пусто. | нить |
| og.url | Для OG: URL. Автоматически используйте canonical значение, если пусто. | нить |
| OG.Image | Для OG: изображение. Установить URL -адрес изображения. | нить |
| Og.Type | Для OG: тип. | "article""book""website""profile" |
| OG.SiteName | Для OG: site_name | нить |
| Custommetatags | Массив объекта для пользовательских метатеток. См. Раздел Custommetatags. | Множество объектов |
| CustomLinkTags | Массив объекта для пользовательских тегов ссылки. См. Раздел CustomLinkTags. | Множество объектов |
Вы можете установить дополнительные метатеги. Пример:
< NextHeadSeo
customMetaTags = { [
{
name : 'foo' ,
content : 'foo-content'
} ,
{
property : 'bar' ,
content : 'bar-content'
}
] }
/>
// Output:
// <head>
// <meta name="foo" content="foo-content"/>
// <meta name="bar" content="bar-content"/>
// </head>Если вы хотите переопределить пользовательские метатеги из другого компонента страницы, используйте те же клавиши для обоих компонентов.
Пример:
// in /pages/_app.tsx
< NextHeadSeo
customMetaTags = { [
{
key : "custom-meta" ,
name : 'foo' ,
content : 'foo-content'
}
] }
/>
// in /pages/example.tsx
< NextHeadSeo
customMetaTags = { [
{
key : "custom-meta" ,
name : 'bar' ,
content : 'bar-content'
}
] }
/ >
// Output:
// <head>
// <meta name="bar" content="bar-content"/>
// </head>Вы можете установить дополнительные теги ссылки. Пример:
< NextHeadSeo
customLinkTags = { [
{
rel : 'foo' ,
href : 'https://example.com/foo'
} ,
{
rel : 'bar' ,
type : 'bar-type' ,
href : 'https://example.com/bar'
} ,
] }
/>
// Output:
// <head>
// <link rel="foo" content="https://example.com/foo"/>
// <link rel="bar" type="bar-type" content="https://example.com/bar"/>
// </head>Если вы хотите переопределить пользовательские теги ссылки из другого компонента страницы, используйте те же клавиши для обоих компонентов. Пример:
// in /pages/_app.tsx
< NextHeadSeo
customLinkTags = { [
{
key : "custom-link" ,
rel : 'foo' ,
content : 'https://example.com/foo'
}
] }
/>
// in /pages/example.tsx
< NextHeadSeo
customLinkTags = { [
{
key : "custom-link" ,
rel : 'bar' ,
type : 'bar-type' ,
ccontent : 'https://example.com/bar'
}
] }
/ >
// Output:
// <head>
// <link rel="bar" type="bar-type" content="https://example.com/bar"/>
// </head>