DEV Community

Reme Le Hane
Reme Le Hane

Posted on • Originally published at remejuan.substack.com

Next.js: Pre-fetching Data with getServerSideProps for SEO Benefits.

In Next.js, the ability to pre-render pages can greatly improve SEO and performance. Using getServerSideProps, you can fetch data at request time, ensuring that your page is rendered with up-to-date data.

When should you use getServerSideProps?

  • Dynamic Content: When you need to load dynamic data for every request (like user-specific pages, or data that frequently changes).
  • SEO Needs: If the data is needed for SEO purposes, pre-rendering it server-side is better than fetching it on the client side.

Example: Using getServerSideProps to Fetch Data

// pages/index.tsx

import { GetServerSideProps } from 'next';

type HomeProps = {
  data: string;
};

export default function Home({ data }: HomeProps) {
  return (
    <div>
      <h1>Server-side Rendered Page</h1>
      <p>{data}</p>
    </div>
  );
}

// This function runs on every request
export const getServerSideProps: GetServerSideProps = async (context) => {
  // Example: Fetch data from an external API or database
  const response = await fetch('https://api.example.com/data');
  const result = await response.json();

  // Pass data to the page component via props
  return {
    props: {
      data: result.message, // Assume the API returns { message: "Hello World" }
    },
  };
};
Enter fullscreen mode Exit fullscreen mode

Key Benefits:

  1. SEO-Friendly: Since the data is rendered on the server, search engines can crawl the fully rendered HTML.
  2. Up-to-date Content: The data is fetched every time the page is requested, ensuring fresh content.
  3. Better UX: No need for loading spinners since data is available when the page loads.

You can leverage this pattern for any page that needs dynamic or user-specific data!

Top comments (0)