FOR DEVELOPERS

How to Build a Next.js App With Server-Side Rendering

Implementing Server-Side Rendering with Next.js

When React was released in May 2013, it created a buzz because it supported single-page applications (SPA) and introduced the concept of a virtual DOM. This made it stand out from other popular frameworks like Ember.js and Angular.

However, because the content of a React application is only injected when a user requests a page, it is difficult to increase website loading times and for SEO crawlers to pick up information from a website.

Enter Next.js, a React framework, which introduced a technique that addressed the shortcomings of React. This article will explore Next.js server-side rendering and its ability to improve an application’s user experience and SEO.

What is server-side rendering and why is it important?

Server-side rendering (SSR) is the process of rendering a client-side application as static HTML on the server. It is important because users expect websites to be fast and seamless. With SSR, you can present a pre-rendered HTML version of your app to users while your JavaScript code loads. This can greatly improve how quickly your website content appears on screen as it makes it easier for SEO crawlers to pick up details of the site.

Getting started with Next.js

Often referred to as ‘The React Framework for the Web’, Next.js is a flexible React framework that extends React with capabilities such as simple page routing, server-side rendering, improved SEO, static site creation, and much more.

To get started with Next.js, you need to install Node.js, which is a JavaScript runtime environment. To verify that Node.js is installed correctly, run the command below in your command prompt.

node -v 

Great! You are all set to create a Next.js app. To begin, open your command prompt or terminal and enter the following command:

npx create-next-app appname

Once the installation is complete, navigate to the project directory and use a code editor of your choice. Then, run the command below to start the development server:

npm run dev

Implementing Next.js server-side rendering

Now, let’s look at how to use server-side rendering to optimize apps and create a better user experience.

Using 'getServerSideProps'

To implement Next.js server-side rendering, you need to include and export a special function that instructs Next.js to handle a page as a server-side rendered page. You can make all your fetch requests to your application programming interface (API) within this function. Next.js will pre-render the page on each request using the data returned by the 'getServerSideProps' function.

export default function Home({ data }) {
  return (
    <main>
      <h1>A List of Blog Posts</h1>
      {data.map((post) => (
        <div key={post.id}>
          <h2>Title: {post.title}</h2>
          <p>Content: {post.body}</p>
        </div>
      ))}
    </main>
  );
}

export async function getServerSideProps() { //Making a get request to an API endpoint to get posts. const response = await fetch("https://jsonplaceholder.typicode.com/posts&quot;); const data = await response.json(); return { props: { data: data, }, }; }

In the above, we made a fetch request to the API endpoint using the fetch API. Once the data is retrieved, we return an object passing the data as a prop. In the Home function, we destructure the prop value, map through the data, and display the responses from the database.

getServerSideProps` function page display.gif

And there you have it: implementing Next.js server-side rendering using the 'getServerSideProps' function.

Note: You should only use "getServerSideProps" when you need to fetch data that changes frequently and have the page update to show the most recent data on your website. This will prevent placing a big load on the server. If the data doesn't need to be frequently updated, it is more efficient to use static site generation (SSG) or client-side rendering (CSR) approaches.

Using 'getStaticProps'

The ‘getStaticProps’ function in Next.js can also be utilized for server-side rendering. It is used to pre-render a page at build time by fetching application data and returning it as props. With it, you can increase the efficiency of your application because it reduces the amount of data that needs to be fetched during runtime.

getStaticProps allows you to generate the page's HTML ahead of time and store it as a static file, eliminating the need to generate the HTML on every request. Let’s take a look.

export default function Home({ data }: any) {
  return (
    <main>
      <h1>A List of Blog Posts</h1>
      {data.map((post: any) => (
        <div key={post.id}>
          <h2>Title: {post.title}</h2>
          <p>Content: {post.body}</p>
        </div>
      ))}
    </main>
  );
}

export async function getStaticProps() { //Making a get request to an API endpoint to get posts const res = await fetch("https://jsonplaceholder.typicode.com/posts&quot;); const data = await res.json(); return { props: { data, }, }; }

In the above, a fetch request is made to the API endpoint. Once the data is successfully retrieved, it is returned as a prop to the Home component where it is destructured and mapped through to display relevant data from the database.

getStaticProps function page display.gif

It's important to note that although getStaticProps can increase the efficiency of an application, it's only suitable for pages with data that doesn’t change frequently. If your data changes frequently, you may want to consider using ‘getServerSideProps’ instead because it ensures that the page content is always up to date.

Lastly, be sure to use these functions only when necessary. If your application requires dynamic and up-to-date content, use getServerSideProps, and if you have data that doesn't change frequently but needs to be pre-rendered at build time, use getStaticProps.

Conclusion

Great job! You’ve now learned how to create a Next.js starter application and how to build a Next.js app with server-side rendering. With the information provided in this article, you and other Next.js developers can ensure that applications have lightning-fast page loading times, improved SEO, and a great user experience.

Author

  • How to Build a Next.js App With Server-Side Rendering

    Jessica Joseph

    Written by Jessica Joseph, a skilled front-end developer and technical writer, with a unique blend of a year of experience in both technical writing and web development.

Frequently Asked Questions

Server-side rendering (SSR) is the process of rendering a client-side application as static HTML on the server.

In comparison to static site generator (SSG) or client-side rendering (CSR), where the server's involvement is minimal after the initial rendering, server-side rendering adds complexity to the server which could reduce the application response time.

Server-side rendering is important because it improves how quickly a website’s content appears on screen. It makes it easier for SEO crawlers to pick up details of the website.

Performance is relative and should be measured based on your system requirement. It is important to consider whether SSR is the right choice for your application. If it is, it should meet your needs.

It is appropriate to use server-side rendering when you need to have dynamic data pre-rendered displayed or updated frequently.

The security of an application is determined by the security mechanisms employed. Server-side rendering (SSR) does not make an application more secure than static site generated apps or client-side rendered apps.

View more FAQs
Press

Press

What’s up with Turing? Get the latest news about us here.
Blog

Blog

Know more about remote work. Checkout our blog here.
Contact

Contact

Have any questions? We’d love to hear from you.

Hire remote developers

Tell us the skills you need and we'll find the best developer for you in days, not weeks.