The Wayback Machine - https://web.archive.org/web/20241013192234/https://www.geeksforgeeks.org/what-is-ssr-in-nextjs/
Open In App

What is SSR in NextJS ?

Last Updated : 18 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Server-Side Rendering (SSR) in Next.js generates HTML on the server for each request, enhancing SEO and initial load times by delivering fully rendered content before it reaches the client.

What is SSR?

SSR or Server Side Rendering is also known as dynamic rendering. In SSR the page is generated each time the server gets a request. Pages on which the data have to change for a particular type of request, those pages use SSR as data is not the same for every request and may vary with it. To use SSR for a page, we need to export an async function called “getServerSideProps“. This async function is called each time a request is made for the page.

Syntax:

export default function Page({ data }) {
return <>YOU CAN DISPLAY YOUR DATA ACCORDINGLY</>;
}
export async function getServerSideProps() {
// Your code
const data = [];

// Passing data to the Page using props
return {
props: { data },
};
}

Note: In place of data you can take any other name of the variable. Also, you can pass multiple props by separating them with commas “,“. 

Below is the Step by Step Implementation

Step 1: Create NextJS Application: You can create a new NextJs project using the below command:

npx create-next-app gfg

Project Structure:

So, right now we have a Next Js application named my-awesome-app whose directory structure is shown in the image below:

Directory structure

Step 2: So, let us create a page with endpoint as “/users” by creating a “users.js” in our “pages” folder and then fetching the users from a dummy API and then showing that data in that endpoint.

Dummy api used:

https://jsonplaceholder.typicode.com/users

Create a users.js file. 

 

created “users.js” file

Step 3: Add the following code to the “pages/users.js” file:

JavaScript
// Inside "pages/users.js"

export default function Users( {data} ){
    return (
        <div>
            <h1>List of Users</h1>
            <ul>
                {data.map((user,index)=>{
                 return <li key={index}>Id : {user.id} , 
                     Name : {user.name} , Email : {user.email}
                 </li>   
                })}
            </ul>
        </div>
    )
}

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

    // Passing data to the Product Page using props
    return {
        props : {data}
    }
}

Step to run the application: Using either of the given 2 commands start the dev server:

npm run dev

Or

yarn run dev

Output: And now go to the “http://localhost:3000/users” to get the output.

Output of the above code



Similar Reads

Node.js Server Side Rendering (SSR) using EJS
Server-side rendering (SSR) is a popular technique for rendering a normally client-side-only single-page app (SPA) on the server and then sending a fully rendered page to the client. The client's JavaScript bundle can then take over and the SPA can operate as normal. SSR technique is helpful in situations where the client has a slow internet connec
3 min read
Benefits of SSR in a React application
Server-Side Rendering (SSR) in a React utility offers several advantages, enhancing both the overall performance and user experience of internet packages. Server-side rendering (SSR) is like a restaurant where the chef (server) prepares the whole dish (web page) in the kitchen (server) before bringing it to your table (browser). Benefits of the use
2 min read
Explain the benefits and limitations of SSR in Redux applications.
SSR in Redux applications means rendering React components on the server side instead of the client's browser. This helps to speed up initial page loads and ensures that search engines can better understand and index your content. With SSR, users get a faster and more seamless experience when accessing your website or application. Benefits of SSR i
2 min read
Describe the process of setting up SSR with Redux.
Server-side rendering (SSR) involves rendering React components on the server before sending them to the client's browser. This results in faster initial page loads, better SEO, and improved user experiences. Understanding the process of setting up SSR with Redux: Install Dependencies: First, ensure you have the necessary dependencies installed, in
2 min read
Server-Side Rendering (SSR) with React Hooks
Server-side rendering (SSR) is a technique used to render web pages on the server side and send the fully rendered page to the client's browser. This approach offers benefits such as improved SEO and faster initial page loads. With the introduction of React Hooks, SSR implementation has become even more streamlined. In this article, we'll explore h
4 min read
Is Server Side Rendering(SSR) always good ?
SSR is a technique used in web development where the HTML of a webpage is generated on the server rather than in the browser. This means when a user requests a webpage, the server prepares the HTML document by executing the necessary logic and sends it to the client’s browser, fully formed and ready to be rendered. This approach is different from C
5 min read
Importance of View Engines in server-side rendering(SSR)
A view engine is a tool used in web development to create dynamic HTML content based on data from the server. It acts as a template processor that allows you to integrate data with predefined HTML templates easily. In this article, we will learn about the Importance of view engines on server side rendering with example. Importance of view engines i
3 min read
How does SSR(Server-Side Rendering) differ from CSR(client-side rendering) ?
Server-Side Rendering (SSR) and Client-Side Rendering (CSR) are two different approaches used in web development to render web pages to users. Each approach has its own set of advantages and disadvantages. In this article, we will learn about the difference between SSR and CSR with examples and features. Table of Content Server-Side Rendering (SSR)
4 min read
How to Set Up Vite for Server-Side Rendering (SSR)?
Vite is a build tool that can be integrated with most modern JS web frameworks like React, Vue, Next.js, or even vanillaJS, and offers a variety of features like Hot Module Reloading (HMR), etc. In this article, we will learn how to setup vite using vanillaJS and SSR. Steps to Set Up Vite for Server-Side Rendering (SSR)Step 1: Create a vanillaJS vi
2 min read
Ultimate Guide to Server-Side Rendering (SSR) with Vite and ReactJS
Server-side rendering (this practice allows making web pages since the browser only enables blank pages) can be defined as one of the current trends in web development. SSR offers many advantages – performance improvement, SEO enhancement, and even convenience for users. As opposed to client-side rendering only after the complete page is loaded, wh
10 min read
Real Estate Listings Platform using NextJS
In this article, we will explore the process of building a real estate listing platform using Next.js. real estate listings platform is a web application that aims to provide users with a comprehensive platform to browse and search for properties. The platform will cater to both buyers and sellers, offering a seamless experience for property listin
6 min read
Document Management System using NextJS
The Document Management System is a web application developed using Next.js, that allows users to efficiently manage their documents. The system provides features for uploading, organizing, and retrieving documents. Users can upload documents through the web interface, which are then stored in local storage. Output Preview: Let us have a look at ho
5 min read
Detecting server vs client in NextJS application
Next.js, a popular React framework, helps you to build powerful web applications with ease. However, managing server-side and client-side execution can pose unique challenges. In this article, we'll explore techniques for detecting server or client execution in Next.js applications. Table of Content What is Server Side Rendering?What is Client Side
5 min read
Difference between NextJS Link vs useRouter in Navigating
NextJS is a React framework that is used to build full-stack web applications. It is used both for front-end as well as back-end. It comes with a powerful set of features to simplify the development of React applications. One of its features is navigation. Navigation is crucial for providing users with seamless browsing experiences. Next.js provide
3 min read
How to Add ChartJS in NextJS 13?
Chart.js in Next.js is the package used to create interactive and visually appealing charts, such as line charts, bar charts, and more, seamlessly integrated into Next.js applications. In this article, we will explore the demonstration of various charts in the NextJS application. Table of Content Implementing Line ChartImplementing Bar ChartSteps t
3 min read
E-commerce Dashboard with NextJS
This project is an E-commerce Dashboard built with Next.js, providing features such as a dynamic sidebar, responsive navigation, order analytics, and most sold items of the week. It shows various features such as product analytics, order management, and user interaction. Output Preview: Prerequisites:Node.jsJavaScriptNext.jsApproachUtilize React an
11 min read
How to Implement File Download in NextJS using an API Route ?
In web development, facilitating file downloads is a common requirement, whether it's providing users with documents, images, or other media files. NextJS, with its versatile API routes and server-side capabilities, offers an elegant solution for implementing file downloads. In this article, we'll explore how to leverage NextJS API routes to enable
5 min read
How To Add Navbar To All Pages In NextJS ?
A navbar is a common UI element used to navigate between different sections or pages of a website. Adding a navbar to all pages ensures consistent navigation across the site. This article will explore how we can add a navbar to all pages In NextJS. Output Preview: Prerequisites:NextJSReactJSReact HooksReact RouterApproachTo add navbar to all the pa
3 min read
How To Implement Multiple Classnames In NextJS ?
When styling components in Next.js, it's common to encounter scenarios where you need to apply multiple classnames for different styling purposes. To implement multiple classnames in Next.js, you can utilize either the built-in classnames package or any other utility library like clsx. We will discuss the different approaches to Implementing Multip
4 min read
How To Implement NextJS Form Validation With Formik And Zod ?
Form validation is a critical aspect of web development to ensure that user input meets specific criteria before submitting data to the server. Implementing form validation in Next.js can be simplified using Formik, a form library for React, and Zod, a schema validation library. Together, they provide a robust solution for managing form state and v
3 min read
How to Create a Sidebar in NextJS & Tailwind CSS?
In web development, sidebars are commonly used to organize navigation elements and provide quick access to different sections of a website. A sidebar is a vertical menu or panel that is typically positioned on the left or right side of the main content area. Prerequisites:Next.jsTailwindJavaScriptSteps to Create NextJS Application:Step 1: Create a
5 min read
How To Setup Multiple Layouts In NextJS?
Next JS Layout components are commonly used to structure the overall layout of a website or web application. They provide a convenient way to maintain consistent header, footer, and other navigation elements across multiple pages In this article, we will learn to set up Multiple Layouts in NextJS. These are one of the most powerful features of Next
4 min read
How To Get NextJS Query Params Serverside?
To access query parameters in Next.js on the server side, you can use the getServerSideProps function. This function allows you to fetch data on each request, and it provides the context object which includes the query parameters. getServerSideProps function will work only on one Page router. You can also use different approaches such as FormData W
5 min read
How To Handle Loading Between Page Changes in NextJS?
To experience smooth transitions between the pages of your Next.js application, you can include a loading indicator that shows the progress of the page being loaded. This can be done by creating a custom spinner component and using it during page transitions. In this article, we will create a custom spinner component and display it between page tra
4 min read
How to Upload Image to MongoDB using Only NextJS 13.4?
Next.js is a React framework that enables functionality such as server-side rendering and generating static websites. MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. Combining Next.js with MongoDB allows you to build full-stack applications where the backend interacts directly with the database and serves dynamic cont
7 min read
How To Scroll To An HTML Element In NextJS?
NextJS has various features that enable smooth scrolling to HTML elements. One method involves using useRef to create a reference to the target element and scrollIntoView to achieve smooth scrolling. Another method, using useEffect and window.scrollBy, sets up an event listener on a button for smooth scrolling when clicked, with useRef hooks to ref
3 min read
How To Implement MongoDB Authentication In NextJS Using NextAuth.Js?
MongoDB authentication integration in Next.js with NextAuth.js enhances the security of web applications. Integrating authentication in a Next.js application using MongoDB as the database can be efficiently achieved with the NextAuth.js library. NextAuth.js is a complete open-source authentication solution for Next.js applications that supports var
3 min read
How to Use Different .env Files with NextJs?
Managing environment variables is important for web development, especially when working with different environments like development, production, and testing. Next.js allows you to use environment variables, which are values you can configure for different environments (like development or production). In this article, we will see how to Use Diffe
3 min read
URL Shortener Service with NextJS
In this article, we will explore the process of building a URL shortener service using NextJS that takes a long URL and generates a shorter, more condensed version that redirects to the original URL when accessed. This shortened URL is typically much shorter and easier to share, especially in situations where character count is limited, such as in
2 min read
NextJS Boilerplate
Next.js is a React framework used to build full-stack web applications. It supports both front-end and backend development. Next.js provides a command to create a project, which generates all the required files known as a boilerplate. In this article, we will learn about the Next.js Boilerplate. What is a Boilerplate?A boilerplate is a collection o
3 min read