Blog Details
Masud Rana
15 Oct 2024
6 min read
As web development continues to evolve, developers are increasingly tasked with finding the best strategies for improving website performance and SEO. Server-Side Rendering (SSR) with Next.js has quickly become a popular solution, allowing developers to strike a balance between fast-loading pages, dynamic data handling, and search engine optimization.
In this blog, we'll explore how SSR works in Next.js, how to create dynamic routes, and how to use the different data-fetching methods like getStaticProps
and getServerSideProps
. By the end, you'll be equipped with practical knowledge to build efficient and scalable web applications using SSR in Next.js.
Server-Side Rendering (SSR) is a method of rendering web pages on the server instead of the client. With SSR, the HTML is generated on the server based on the user’s request and is then sent to the client. This approach offers key benefits:
Improved Performance: Since the content is pre-rendered, the initial page load is faster compared to client-side rendering (CSR), where the browser has to download JavaScript and fetch data before rendering.
Better SEO: Search engines can easily crawl and index the fully-rendered HTML, making SSR an ideal choice for content-heavy or SEO-focused sites like blogs, e-commerce platforms, and news sites.
Next.js, a React framework, simplifies the implementation of SSR by providing out-of-the-box support. Let’s dive into how you can harness this power.
Dynamic routing in Next.js is a powerful feature that allows us to create flexible URLs that adapt to various parameters. For example, if you're building a blog, you might want to display a different article based on the post ID.
In Next.js, dynamic routes are achieved by using square brackets ([]
) to indicate a dynamic segment in your file structure.
Let’s assume you want to create a dynamic blog page where each blog post has a unique ID. You can do this by creating a file under the pages
directory:
/pages/blog/[id].js
Inside this file, you can fetch data specific to the blog post using SSR.
Next.js provides multiple data-fetching methods, each tailored for different use cases. In this blog, we'll focus on two methods: getServerSideProps
and getStaticProps
.
When you need fresh data on every request, such as in a dashboard or dynamic content that changes frequently, getServerSideProps
is your go-to method. It runs on the server side and fetches data before rendering the page.
Here’s how you can implement it in a Next.js page:
export async function getServerSideProps(context) {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${context.params.id}`);
const data = await res.json();
return {
props: { post: data },
};
}
export default function BlogPost({ post }) {
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
}
In this example, we are using getServerSideProps
to fetch a blog post based on its id
. This ensures that every time a user visits a blog page, the most up-to-date data is fetched and rendered on the server.
On the other hand, when your content doesn’t change often (such as a marketing page or a blog with static content), you can use getStaticProps
. This method pre-fetches data at build time and serves the same static HTML to all users.
Here’s an example using getStaticProps
:
export async function getStaticProps() {
const res = await fetch('https://jsonplaceholder.typicode.com/posts');
const data = await res.json();
return {
props: { posts: data },
};
}
export default function BlogList({ posts }) {
return (
<div>
{posts.map(post => (
<div key={post.id}>
<h2>{post.title}</h2>
<p>{post.body}</p>
</div>
))}
</div>
);
}
In this case, the blog posts are fetched once at build time. This approach is ideal for content that doesn't change frequently, as it reduces server load and results in faster response times.
Let’s take a practical approach by building a simple blog application with dynamic routes and server-side data fetching.
First, ensure you have Next.js installed. If not, you can create a new project using the following command:
npx create-next-app my-blog
cd my-blog
Next, create a dynamic route for your blog posts under the pages/blog/[id].js
directory.
mkdir -p pages/blog
touch pages/blog/[id].js
In the pages/blog/[id].js
file, add the following code:
import { useRouter } from 'next/router';
import Head from 'next/head';
export async function getServerSideProps(context) {
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/${context.params.id}`);
const post = await res.json();
return {
props: { post },
};
}
export default function BlogPost({ post }) {
return (
<div>
<Head>
<title>{post.title}</title>
</Head>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
);
}
In this example, we are using getServerSideProps
to fetch the blog post based on the ID from the URL. This ensures that the content is server-rendered and up-to-date on every request.
Now, run your application:
npm run dev
Visit http://localhost:3000/blog/1
to see the server-side rendered blog post.
Server-Side Rendering with Next.js offers a powerful way to optimize both performance and SEO for modern web applications. Whether you're building dynamic routes or leveraging efficient data-fetching methods like getServerSideProps
, SSR ensures a faster, more responsive, and SEO-friendly user experience.
By understanding the nuances of SSR and learning when to apply it, you can create highly performant applications that cater to both user experience and search engine visibility. If you're working on content-heavy sites or looking to boost SEO, SSR with Next.js should be at the top of your list.
Don’t worry, we don’t spam!