nextjs
  1. nextjs-server-side-rendering-ssr

Next.js Server-Side Rendering (SSR)

Heading h1

Next.js is a React framework that provides an easier way to build React applications. It offers server-side rendering out of the box, ensuring your application loads faster and has better SEO performance.

Syntax

Next.js provides a simple API to perform server-side rendering (SSR) of your web application. Here's the syntax to use:

// pages/index.js

function HomePage({ data }) {
  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.content}</p>
    </div>
  )
}

export async function getServerSideProps() {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts/1')
  const data = await res.json()

  return {
    props: { data }
  }
}

export default HomePage;

Example

  • In the above sample code, we are fetching data from an external API using the getServerSideProps function.
  • The data object returned from the API call is passed as props to the HomePage component.
  • The component then renders the title and content fetched from the API.

Output

The output in the browser will show the fetched data from the API in the format:

Hello Next.js!
Next.js is a React framework that provides an easier way to build React applications.

Explanation

Next.js provides a special function called getServerSideProps which runs on the server-side before rendering the page. This function is used to fetch data, which is then passed as props to the page component. The component is then rendered on the server-side.

The advantage of SSR is that HTML is returned to the client instead of JavaScript. This results in faster load times and better SEO performance as search engines can crawl and index the pages.

Use

Next.js SSR can be used to improve the performance and SEO of your application. It can be particularly useful for large-scale applications that need to be optimized for search engines with fast load times.

Important Points

  • getServerSideProps fetches data from an external API and passes it as props to the component.
  • SSR improves performance and SEO for Next.js applications.
  • HTML is returned to the client instead of JavaScript.
  • SSR is particularly useful for large-scale applications.

Summary

Next.js SSR is an easy and effective way to optimize your application's performance and SEO. It offers simple syntax and can be used to fetch data from external APIs with ease. Understanding the basics of SSR in Next.js is vital for building high-performance applications.

Published on: