简体   繁体   中英

How to improve SEO with getServerSideProps() in NextJS?

I have a website that will show dynamic data (Articles), ie data that changes hourly.

I therefore have opted to use getServerSideProps() from NextJS.

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,
        }
    }
}

I could not use getStaticPaths() because the data changes so frequently, an hour after building the site and all the static paths would point to out-of-date articles, and all the new articles would not have any paths pointing to them. I also looked at ISR however this also wouldn't work as it relies on knowing the paths in advance.

My issue arises that because getServerSideProps() is completely dynamic, search engines do not see any of the dynamic pages (which is pretty much the entire site), and therefore I do not rank well.

Is there a way to use getServerSideProps() with some kind of caching, that will allow search engines to see the pages? If not, is there an alternative framework I can use that allows dynamic pages while retaining some SEO performance?

First of all, reduce the number of dynamic pages. too many dynamic pages will put your app at risk of cloaking and google hates it.

Generate sitemap. sitemap will improve the SEO but it is very hard for getServerSideProps because those functions are not available during build time. Use this npm package: next-sitemap . it helps for dynamic pages too.

Server side index-sitemaps (getServerSideSitemapIndex) Here's a sample script to generate index-sitemap on server side.Create pages/server-sitemap-index.xml/index.tsx page and add the following content.

// 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() {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM