MERN

⌘K
  1. Home
  2. Docs
  3. MERN
  4. Server-Side Rendering (SSR)

Server-Side Rendering (SSR)

For the blog list page (app/blog/page.tsx), you would fetch and display a list of blog posts. For the individual post detail page (app/blog/[slug]/page.tsx), you would fetch and display the details for a single post based on its slug. Here’s how you would implement these components in Next.js, using Server-Side Rendering (SSR) with getServerData.

Blog List Page: app/blog/page.tsx

// app/blog/page.tsx
import Head from 'next/head';

export async function getServerData() {
  // Replace with the actual URL to your WordPress blog API
  const res = await fetch('https://your-wordpress-site.com/wp-json/wp/v2/posts');
  const posts = await res.json();

  return {
    props: { posts },
  };
}

export default function BlogPage({ posts }) {
  return (
  <>
        <Head>
        <title>Blog | My Awesome Website</title>
        <meta name="description" content="Read the latest articles on My Awesome Website." />
        {/* Other SEO tags */}
      </Head>
      
    <div>
      <h1>Blog</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            {/* Make sure the path here matches your file structure */}
            <a href={`/blog/${post.slug}`}>{post.title.rendered}</a>
          </li>
        ))}
      </ul>
    </div>
    </>
  );
}
JavaScript

Individual Post Detail Page: app/blog/[slug]/page.tsx





// app/blog/[slug]/page.tsx
import Head from 'next/head';
import { useRouter } from 'next/router';

export async function getServerData(context) {
  // Replace with the actual URL to your WordPress blog API
  const res = await fetch(`https://your-wordpress-site.com/wp-json/wp/v2/posts?slug=${context.params.slug}`);
  const postDetails = await res.json();
  const post = postDetails.length > 0 ? postDetails[0] : null;

  return {
    props: { post },
  };
}

export default function PostPage({ post }) {
  const router = useRouter();

  if (router.isFallback || !post) {
    return <div>Loading...</div>;
  }

  return (
      <>
      <Head>
        <title>{post.title.rendered} | My Awesome Website</title>
        <meta name="description" content={`Read this post: ${post.title.rendered} on My Awesome Website.`} />
        {/* Other SEO tags */}
      </Head>
    <article>
      <h1>{post.title.rendered}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.content.rendered }} />
    </article>
     </>
  );
}
JavaScript

Articles

How can we help?