Server-Side Rendering (SSR) with Next.js and JavaScript


In the world of web development, delivering a fast and seamless user experience is crucial. One way to achieve this is through Server-Side Rendering (SSR), a technique that allows rendering web pages on the server before sending them to the client. SSR offers numerous benefits, including improved performance, SEO optimization, and better user interaction. In this article, we will explore the fundamentals of SSR using Next.js, a popular JavaScript framework for building server-rendered React applications.

What is Server-Side Rendering (SSR)?

Traditionally, web applications have relied on client-side rendering, where the entire rendering process occurs on the browser using JavaScript. This approach works well for small applications, but it can lead to slower initial page loads, poor SEO performance, and limited accessibility.

Server-Side Rendering, on the other hand, involves generating the complete HTML content on the server and sending it to the client. The client then receives a fully rendered page, ready to be displayed to the user. This method allows search engines to crawl the page more effectively and improves the perceived performance for users.

Introducing Next.js

Next.js is a React framework that provides built-in server-side rendering capabilities. It simplifies the process of building SSR applications by abstracting away the complexities of server-side setup and configuration. Next.js also offers features like automatic code splitting, client-side rendering, and static site generation, making it a versatile choice for modern web development.

Setting up a Next.js Project

To get started with Next.js, ensure that Node.js is installed on your machine. Create a new directory for your project and initialise it using the following command −

npx create-next-app my-next-app

This command sets up a new Next.js project with the necessary files and dependencies. Navigate into the project directory by running −

cd my-next-app

Once inside the project directory, start the development server using the following command −

npm run dev

Next.js will launch a local development server on http://localhost:3000, and you can see your application running in the browser.

Creating a Server-Side Rendered Page

Next.js makes it incredibly simple to create server-side rendered pages. In the project structure, navigate to the pages directory and create a new file named about.js. This file will represent the /about route in our application.

In about.js, add the following code −

function About() {
   return (
      <div>
         <h1>About Page</h1>
         <p>This is the server-side rendered About page.</p>
      </div>
   );
}

export default About;

Save the file, and if the Next.js development server is running, you can navigate to http://localhost:3000/about to see the rendered page.

Let's take a closer look at the code. The About component is a React functional component that returns JSX, which represents the content of the About page. In this case, it renders a <div> element containing an <h1> heading and a <p> paragraph.

The export default About statement at the end exports the About component as the default export, which allows Next.js to recognize it as a server-side rendered page.

Upon visiting the /about route, the server will render the About component, and the client will receive the complete HTML representation of the page. This approach ensures that the page is fully rendered before it is sent to the user, improving performance and SEO.

Dynamic Server-Side Rendering

Next.js also supports dynamic server-side rendering, allowing us to fetch data from an external API or perform server-side computations before rendering the page. This enables us to provide dynamic content to the user without relying on client-side JavaScript.

To demonstrate dynamic server-side rendering, let's create a page that fetches data from a mock API. In the pages directory, create a new file named users.js −

function Users({ users }) {
   return (
      <div>
         <h1>User List</h1>
         <ul>
            {users.map((user) => (
               <li key={user.id}>{user.name}</li>
            ))}
         </ul>
      </div>
   );
}

export async function getServerSideProps() {
   const response = await  fetch('https://api.example.com/users');
   const users = await response.json();

   return {
      props: {
         users,
      },
   };
}

export default Users;

Explanation

In the code above, we define a functional component Users that receives the users data as a prop. It renders a list of users using the received data. The getServerSideProps function is an asynchronous function that fetches data from an external API (https://api.example.com/users in this example).

Inside getServerSideProps, we use the fetch function to make an HTTP request to the API and retrieve the user data. We then parse the response as JSON and assign it to the user's variable. Finally, we return an object with a props property, which contains the fetched users data.

When a user visits the /users route, Next.js will invoke the getServerSideProps function on the server to fetch the data. The fetched users data will be passed as a prop to the Users component for rendering. This ensures that the page is always rendered with the most up-to-date data on each request.

Dynamic server-side rendering is a powerful feature that allows us to build data-driven pages and deliver personalised content to users. By fetching data on the server, we can optimise performance and ensure a consistent user experience across different devices and network conditions.

Conclusion

Server-Side Rendering (SSR) with Next.js and JavaScript offers an efficient approach to building high-performance web applications. By leveraging Next.js's server-side rendering capabilities, we can deliver fully rendered pages to users, improving performance, search engine visibility, and overall user experience.

This article provided an introduction to SSR, walked through setting up a Next.js project, and demonstrated how to create server-side rendered pages. We explored the benefits of server-side rendering and how Next.js simplifies the process of implementing SSR in a React application.

Updated on: 25-Jul-2023

230 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements