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
-
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.
-
Next.js:
- A React framework that enables SSR, static site generation (SSG), and other advanced features.
- Simplifies the setup and configuration for SSR.
-
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:
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.
- A functional React component that receives
-
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:
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
- Objective: Create a Next.js page that fetches and displays weather data for a given city using SSR.
- API: Use the OpenWeatherMap API (https://openweathermap.org/api).
Steps
-
Sign Up for an API Key:
- Sign up at OpenWeatherMap and get an API key.
-
Create a New Page:
- Create a new file
pages/weather.js
.
- Create a new file
-
Fetch Weather Data:
- Use
getServerSideProps
to fetch weather data for a city (e.g., London).
- Use
-
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
- What is React?
- Setting Up the Development Environment
- Hello World in React
- JSX: JavaScript Syntax Extension
Module 2: React Components
- Understanding Components
- Functional vs Class Components
- Props: Passing Data to Components
- State: Managing Component State
Module 3: Working with Events
Module 4: Advanced Component Concepts
- Lifting State Up
- Composition vs Inheritance
- React Lifecycle Methods
- Hooks: Introduction and Basic Usage
Module 5: React Hooks
Module 6: Routing in React
Module 7: State Management
- Introduction to State Management
- Context API
- Redux: Introduction and Setup
- Redux: Actions and Reducers
- Redux: Connecting to React
Module 8: Performance Optimization
- React Performance Optimization Techniques
- Memoization with React.memo
- useMemo and useCallback Hooks
- Code Splitting and Lazy Loading
Module 9: Testing in React
- Introduction to Testing
- Unit Testing with Jest
- Testing Components with React Testing Library
- End-to-End Testing with Cypress
Module 10: Advanced Topics
- Server-Side Rendering (SSR) with Next.js
- Static Site Generation (SSG) with Next.js
- TypeScript with React
- React Native: Building Mobile Apps