Blog>
Snippets

Basic Setup of a React Server Component in Next.js 14

Demonstrate how to create and utilize a simple React Server Component in a Next.js 14 application, to render data fetched on the server side.
// pages/index.js
import React from 'react';
import FetchData from '../components/FetchData.server';

export default function HomePage() {
  return (
    <div>
      <h1>Welcome to the Home Page</h1>
      {/* Render the server component here */}
      <FetchData />
    </div>
  );
}
This is the main page component (`pages/index.js`) where we import and render our server component, `FetchData`, which will fetch and display data server-side.
// components/FetchData.server.js
import React from 'react';

// This is a server component indicated by the .server.js file name
export default function FetchData() {
  // Simulated fetched data
  const data = 'Server-side fetched data';

  // Return JSX rendered on the server
  return (
    <div>
      <h2>Data from Server Component:</h2>
      <p>{data}</p>
    </div>
  );
}
The React server component (`components/FetchData.server.js`) is responsible for fetching and rendering data on the server. Here, a simulated data fetch is shown for demonstration purposes. In a real application, this component would fetch data from an API or database.
// next.config.js
module.exports = {
  experimental: {
    serverComponents: true,
  },
  // ...remaining config
};
The Next.js configuration file (`next.config.js`) where server components are enabled with the experimental flag. This may be needed in your setup, depending on the Next.js version and the evolution of this feature.