HomeProjectsBlogSnippetsVideos
    ← Back to Next.Js

    Server Side Rendering

    2 snippets in Next.Js - Server Side Rendering

    Server-side data fetching

    Mock API call or data source (replace with your actual data source)

    1// pages/index.js
    2import Head from "next/head";
    3
    4// Server-side data fetching
    5export async function getServerSideProps(context) {
    6  // Mock API call or data source (replace with your actual data source)
    7  const fetchPosts = async () => {
    8    // Simulating an API call with a delay
    9    await new Promise((resolve) => setTimeout(resolve, 500));
    10    return [
    11      { id: 1, title: "Post 1", content: "This is the first post." },
    12      { id: 2, title: "Post 2", content: "This is the second post." },
    13      { id: 3, title: "Post 3", content: "This is the third post." },
    14    ];
    15  };
    16
    17  try {
    18    const posts = await fetchPosts();
    19
    20    // Return props to the page
    21    return {
    22      props: {
    23        posts,
    24        fetchedAt: new Date().toISOString(), // Example of server-side timestamp
    25      },
    26    };
    27  } catch (error) {
    28    // Handle errors gracefully
    29    return {
    30      props: {
    31        posts: [],
    32        error: "Failed to fetch posts",
    33      },
    34    };
    35  }
    36}
    javascript

    Page component

    Page component example

    1export default function Home({ posts, fetchedAt, error }) {
    2  return (
    3    <div className="min-h-screen bg-gray-100">
    4      <Head>
    5        <title>Next.js 15 SSR Example</title>
    6        <meta name="description" content="Server-side rendering with Next.js 15" />
    7      </Head>
    8
    9      <main className="container mx-auto px-4 py-8">
    10        <h1 className="text-3xl font-bold text-center mb-6">
    11          Server-Side Rendered Posts
    12        </h1>
    13
    14        {error ? (
    15          <p className="text-red-500 text-center">{error}</p>
    16        ) : (
    17          <>
    18            <p className="text-sm text-gray-600 text-center mb-4">
    19              Data fetched at: {fetchedAt}
    20            </p>
    21            <ul className="space-y-4">
    22              {posts.map((post) => (
    23                <li
    24                  key={post.id}
    25                  className="p-4 bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow"
    26                >
    27                  <h2 className="text-xl font-semibold">{post.title}</h2>
    28                  <p className="text-gray-700">{post.content}</p>
    29                </li>
    30              ))}
    31            </ul>
    32          </>
    33        )}
    34      </main>
    35    </div>
    36  );
    37}
    javascript