Chapter 9: Server-Side Rendering (SSR)
Chapter 9 of 15
Chapter 9: Server-Side Rendering (SSR)
9.1 Next.js Basics
Next.js is a React framework that enables server-side rendering, static site generation, and other performance optimizations.
// pages/index.js - Server-side rendered page
export default function Home({ data }) {
return (
<div>
<h1>Home Page</h1>
<p>{data.message}</p>
</div>
);
}
// getServerSideProps - runs on server for each request
export async function getServerSideProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: { data }
};
}
9.2 Static Site Generation (SSG)
// getStaticProps - runs at build time
export async function getStaticProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: { data },
revalidate: 60 // Revalidate every 60 seconds (ISR)
};
}
// getStaticPaths - for dynamic routes
export async function getStaticPaths() {
const res = await fetch('https://api.example.com/posts');
const posts = await res.json();
const paths = posts.map(post => ({
params: { id: post.id.toString() }
}));
return { paths, fallback: false };
}
9.3 API Routes
// pages/api/users.js
export default function handler(req, res) {
if (req.method === 'GET') {
res.status(200).json({ users: [] });
} else if (req.method === 'POST') {
// Handle POST request
res.status(201).json({ message: 'User created' });
}
}
9.4 React Server Components
// app/page.js (App Router)
// Server Component by default
async function Page() {
const data = await fetch('https://api.example.com/data');
const json = await data.json();
return (
<div>
<h1>{json.title}</h1>
<ClientComponent data={json} />
</div>
);
}
// app/client-component.js
'use client'; // Client Component directive
export default function ClientComponent({ data }) {
const [count, setCount] = useState(0);
return <div>{data.content}</div>;
}