Table of Contents
- Introduction
- What is Next.js?
- Setting Up a Next.js Project
- Understanding File-Based Routing
- Server-Side Rendering (SSR) in Next.js
- Static Site Generation (SSG) in Next.js
- Comparison of SSR vs SSG
- Using getServerSideProps for SSR
- Using getStaticProps for SSG
- Next.js API Routes
- Conclusion
1. Introduction
Next.js is a powerful React framework that allows you to build full-stack applications with ease. It provides out-of-the-box features like file-based routing, server-side rendering (SSR), and static site generation (SSG), which make it easy to build fast, SEO-friendly applications. In this module, we’ll dive deep into how Next.js works and explore key features such as SSR, SSG, and the simple yet powerful file-based routing system.
2. What is Next.js?
Next.js is a React framework created by Vercel that allows for both client-side and server-side rendering. It simplifies the process of building modern React applications by offering:
- File-based routing: Automatic routing based on the file structure.
- Server-side rendering (SSR): Allows rendering pages on the server, improving SEO and performance.
- Static site generation (SSG): Enables pre-rendering of pages at build time, making the app even faster.
- API routes: Ability to build server-side APIs within the same project.
3. Setting Up a Next.js Project
To begin with Next.js, you’ll first need to set up a project. Follow these steps:
- Create a new Next.js application: You can easily create a Next.js app using Create Next App. bashCopyEdit
npx create-next-app@latest my-nextjs-app cd my-nextjs-app npm run dev
This will start a local development server athttp://localhost:3000
. - Project structure: Next.js uses a standard folder structure: bashCopyEdit
/pages - Contains your pages /public - Static assets like images /styles - CSS/Styling
4. Understanding File-Based Routing
One of the standout features of Next.js is file-based routing. This means the files you create inside the /pages
directory automatically correspond to routes in your application.
- Default Routing Example:
/pages/index.js
maps to/
/pages/about.js
maps to/about
/pages/contact.js
maps to/contact
- Dynamic Routing: Next.js allows dynamic routing using file names enclosed in square brackets:
/pages/[id].js
corresponds to a dynamic route like/post/1
,/post/2
, etc.- You can access the dynamic route parameter in the component using
useRouter()
.
// /pages/[id].js import { useRouter } from 'next/router'; const Post = () => { const router = useRouter(); const { id } = router.query; return <h1>Post ID: {id}</h1>; }; export default Post;
5. Server-Side Rendering (SSR) in Next.js
Server-Side Rendering (SSR) allows pages to be rendered on the server at the time of the request. This ensures that the page is fully rendered with the required data before being sent to the client. SSR is especially useful for SEO and faster initial page loads.
- Using
getServerSideProps
: In Next.js, you can enable SSR for a page by exporting an asynchronous function calledgetServerSideProps
. This function will run on the server before the page is rendered. Example: jsxCopyEdit// pages/ssr.js export async function getServerSideProps() { const res = await fetch('https://jsonplaceholder.typicode.com/posts'); const data = await res.json(); return { props: { posts: data } }; } const SSRPage = ({ posts }) => { return ( <div> <h1>Server Side Rendered Posts</h1> {posts.map(post => ( <div key={post.id}> <h2>{post.title}</h2> <p>{post.body}</p> </div> ))} </div> ); }; export default SSRPage;
6. Static Site Generation (SSG) in Next.js
Static Site Generation (SSG) allows you to pre-render pages at build time, so the content is ready when the page is loaded. This results in faster page loads and better SEO.
- Using
getStaticProps
: This function is executed at build time to fetch the data, which will then be passed as props to the page. Example: jsxCopyEdit// pages/ssg.js export async function getStaticProps() { const res = await fetch('https://jsonplaceholder.typicode.com/posts'); const data = await res.json(); return { props: { posts: data } }; } const SSGPage = ({ posts }) => { return ( <div> <h1>Static Site Generated Posts</h1> {posts.map(post => ( <div key={post.id}> <h2>{post.title}</h2> <p>{post.body}</p> </div> ))} </div> ); }; export default SSGPage;
7. Comparison of SSR vs SSG
Both SSR and SSG are powerful techniques for rendering React applications, but they have different use cases:
- SSR:
- Ideal for dynamic data that changes frequently or based on user input.
- Ensures that each page request is served with fresh data.
- Can impact performance if the data fetching is slow.
- SSG:
- Ideal for static content that doesn’t change often.
- Great for SEO and performance because pages are pre-built.
- Cannot be used when content needs to be highly dynamic or personalized.
8. Using getServerSideProps
for SSR
When using SSR, Next.js will run getServerSideProps
every time a user requests a page. This is useful for content that needs to be up-to-date on every request, like user dashboards or real-time data.
Example of SSR with a user-specific page:
jsxCopyEdit// pages/dashboard.js
export async function getServerSideProps(context) {
const userId = context.params.id;
const res = await fetch(`https://api.example.com/user/${userId}`);
const user = await res.json();
return { props: { user } };
}
const Dashboard = ({ user }) => {
return <h1>Welcome {user.name}!</h1>;
};
export default Dashboard;
9. Using getStaticProps
for SSG
For SSG, you use getStaticProps
to fetch data at build time, meaning the page is generated once and cached until the next build.
Example of SSG:
jsxCopyEdit// pages/products.js
export async function getStaticProps() {
const res = await fetch('https://api.example.com/products');
const products = await res.json();
return { props: { products } };
}
const Products = ({ products }) => {
return (
<div>
<h1>Product List</h1>
{products.map(product => (
<div key={product.id}>
<h2>{product.name}</h2>
<p>{product.description}</p>
</div>
))}
</div>
);
};
export default Products;
10. Next.js API Routes
Next.js allows you to create API routes inside the pages/api
directory. These API routes can handle server-side logic, such as fetching data or interacting with a database.
Example of an API route:
jsxCopyEdit// pages/api/products.js
export default async function handler(req, res) {
const response = await fetch('https://api.example.com/products');
const data = await response.json();
res.status(200).json(data);
}
11. Conclusion
Next.js is a powerful React framework that provides file-based routing, SSR, SSG, and API routes, making it a great choice for building scalable, SEO-friendly applications. By using SSR and SSG, you can ensure your app is fast, dynamic, and optimized for search engines.