如何使用 NextJS 中的 getServerSideProps() 改进 SEO?

问题描述 投票:0回答:2

我有一个网站,将显示动态数据(文章),即每小时变化的数据。

因此我选择使用 NextJS 的

getServerSideProps()

export async function getServerSideProps() {
    const url = process.env.NEXT_PUBLIC_API_URL

    const articles = await fetch(url + 'article').then(res => res.json()).catch(err => console.error(err))

    console.log("articles", articles);

    return {
        props: {
            articles,
        }
    }
}

我无法使用

getStaticPaths()
,因为数据变化太频繁,建站一小时后所有静态路径都会指向过时的文章,而所有新文章都不会有任何路径指向它们。我也看过
ISR
但这也行不通,因为它依赖于提前了解路径。

我的问题是,因为

getServerSideProps()
是完全动态的,搜索引擎看不到任何动态页面(几乎是整个网站),因此我的排名不好。

有没有办法将

getServerSideProps()
与某种缓存一起使用,从而允许搜索引擎查看页面?如果没有,我可以使用替代框架来允许动态页面,同时保留一些 SEO 性能吗?

reactjs next.js seo server-side-rendering
2个回答
0
投票

首先,减少动态页面的数量。太多的动态页面会让你的应用面临

cloaking
的风险,而谷歌讨厌它。

生成站点地图。站点地图将改善 SEO,但对于

getServerSideProps
来说非常困难,因为这些功能在构建期间不可用。使用这个 npm 包:next-sitemap。它对动态页面也有帮助。

服务器端索引站点地图(getServerSideSitemapIndex) 这是在服务器端生成index-sitemap的示例脚本。创建pages/server-sitemap-index.xml/index.tsx页面并添加以下内容。

// pages/server-sitemap-index.xml/index.tsx
import { getServerSideSitemapIndex } from 'next-sitemap'
import { GetServerSideProps } from 'next'

export const getServerSideProps: GetServerSideProps = async (ctx) => {
  // Method to source urls from cms
  // const urls = await fetch('https//example.com/api')

  return getServerSideSitemapIndex(ctx, [
    'https://example.com/path-1.xml',
    'https://example.com/path-2.xml',
  ])
}

// Default export to prevent next.js errors
export default function SitemapIndex() {}

-1
投票

要在 Next.js 中启用站点地图,请使用 getServerSideProps 函数,如官方文档中所述,该文档还强调了其 SEO 和索引优势。

请参阅官方 Next.js 站点地图 文档:- https://nextjs.org/learn/seo/crawling-and-indexing/xml-sitemaps 了解详细说明。严格按照在 Next.js 应用程序中设置站点地图的步骤进行操作。如果您遇到问题或有疑问,请随时在此论坛寻求帮助。

© www.soinside.com 2019 - 2024. All rights reserved.