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!

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay