Introduction

Server-Side Rendering (SSR) is a technique used to render web pages on the server instead of the client. This can improve performance and SEO by delivering fully rendered pages to the client. Next.js is a popular React framework that provides built-in support for SSR.

Key Concepts

  1. Server-Side Rendering (SSR):

    • Rendering a web page on the server and sending the fully rendered HTML to the client.
    • Improves initial load time and SEO.
  2. Next.js:

    • A React framework that enables SSR, static site generation (SSG), and other advanced features.
    • Simplifies the setup and configuration for SSR.
  3. getServerSideProps:

    • A Next.js function used to fetch data on the server side before rendering the page.

Setting Up Next.js

Step 1: Create a New Next.js Project

First, ensure you have Node.js installed. Then, create a new Next.js project using the following commands:

npx create-next-app@latest my-nextjs-app
cd my-nextjs-app
npm run dev

This will set up a new Next.js project and start the development server.

Step 2: Create a Page with SSR

Next.js uses the pages directory to define routes. Create a new file pages/ssr.js:

// pages/ssr.js
import React from 'react';

const SSRPage = ({ data }) => {
  return (
    <div>
      <h1>Server-Side Rendering with Next.js</h1>
      <p>Data fetched from the server:</p>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};

export async function getServerSideProps() {
  // Fetch data from an API or database
  const res = await fetch('https://api.example.com/data');
  const data = await res.json();

  // Pass data to the page via props
  return { props: { data } };
}

export default SSRPage;

Explanation

  • SSRPage Component:

    • A functional React component that receives data as a prop and displays it.
  • getServerSideProps Function:

    • This function runs on the server side before rendering the page.
    • It fetches data from an API and passes it to the component as props.

Step 3: Run the Application

Start the development server if it's not already running:

npm run dev

Navigate to http://localhost:3000/ssr in your browser. You should see the data fetched from the server displayed on the page.

Practical Exercise

Exercise: Implement SSR for a Weather App

  1. Objective: Create a Next.js page that fetches and displays weather data for a given city using SSR.
  2. API: Use the OpenWeatherMap API (https://openweathermap.org/api).

Steps

  1. Sign Up for an API Key:

    • Sign up at OpenWeatherMap and get an API key.
  2. Create a New Page:

    • Create a new file pages/weather.js.
  3. Fetch Weather Data:

    • Use getServerSideProps to fetch weather data for a city (e.g., London).
  4. Display the Data:

    • Display the fetched weather data on the page.

Solution

// pages/weather.js
import React from 'react';

const WeatherPage = ({ weather }) => {
  return (
    <div>
      <h1>Weather in {weather.name}</h1>
      <p>Temperature: {weather.main.temp}°C</p>
      <p>Weather: {weather.weather[0].description}</p>
    </div>
  );
};

export async function getServerSideProps() {
  const apiKey = 'YOUR_API_KEY';
  const city = 'London';
  const res = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`);
  const weather = await res.json();

  return { props: { weather } };
}

export default WeatherPage;

Explanation

  • WeatherPage Component:

    • Displays the weather data for the specified city.
  • getServerSideProps Function:

    • Fetches weather data from the OpenWeatherMap API and passes it to the component as props.

Conclusion

In this section, you learned about Server-Side Rendering (SSR) with Next.js. You set up a Next.js project, created a page with SSR, and fetched data on the server side using getServerSideProps. You also completed a practical exercise to implement SSR for a weather app. This knowledge prepares you for more advanced topics like Static Site Generation (SSG) and integrating TypeScript with React.

React Course

Module 1: Introduction to React

Module 2: React Components

Module 3: Working with Events

Module 4: Advanced Component Concepts

Module 5: React Hooks

Module 6: Routing in React

Module 7: State Management

Module 8: Performance Optimization

Module 9: Testing in React

Module 10: Advanced Topics

Module 11: Project: Building a Complete Application

© Copyright 2024. All rights reserved