Server-side rendering (SSR) has become an essential technique for building fast, search engine optimised web applications. In this post, I will try to explore how to leverage SSR in Next.js to boost performance and SEO.
What is Server-Side Rendering?
The browser receives a simple HTML page and JavaScript code when using typical client-side rendered apps. After that, the JavaScript retrieves data from APIs and produces the page. As a result, initial load times are slower and SEO crawling is unreliable.
Before transmitting the page to the client, the server prepares a completely rendered HTML page using SSR. This allows the website to load faster and for search engine crawlers to see it correctly. SSR is supported by Next.js out of the box.
Faster Initial Page Loads
Pages rendered by Next.js on the server skip the initial empty loading state. The HTML is fully rendered, so the browser can start processing the page immediately.
For example, here is how we can use getServerSideProps
in Next.js to pre-render a page with data:
export async function getServerSideProps(context) {
const res = await fetch(`https://.../data`)
const data = await res.json()
return {
props: {
data
}
}
}
export default function Page({ data }) {
// data is pre-rendered
}
Consistent SEO Crawling
Search engine crawlers receive a fully rendered HTML page from Next.js rather than having to wait for JavaScript execution. This means pages have consistent SEO regardless of JS complexity.
We can verify rendering with getInitialProps
:
export async function getInitialProps(context) {
return {
props: {
title: 'My SEO Optimized Page'
}
}
}
export default function Page(props) {
return <h1>{props.title}</h1>
}
The page title will be present in the generated HTML and readable by crawlers.
Scalable Performance
Next.js offers multiple forms of SSR to fit different performance needs.
-
getServerSideProps
- Execute code on every request -
getStaticProps
- Build HTML at build time -
getInitialProps
- Legacy option
Choosing the best technique is dependent on the frequency and volume of your material.
In conclusion, leveraging Next.js SSR is an effective technique to improve website speed and SEO. The ability to pre-render pages enables performance advantages and SEO capabilities that other frameworks lack.
Top comments (0)