Table of contents
1.
Introduction
2.
What is getServerSideProps?
3.
When is getServerSideProps executed?
4.
When should we use getServerSideProps?
4.1.
Behavior
4.2.
Error Handling
4.3.
Edge Cases
4.4.
Edge Runtime
4.5.
Caching with Server-Side Rendering (SSR)
5.
Understanding the distinction between client-side and server-side render applications
5.1.
Drawbacks
6.
API Routes or getServerSideProps
7.
How can we use getServerSideProps to get data from the server?
7.1.
Usage
7.2.
Advantages
7.3.
Example Usage
7.4.
Example
8.
Frequently Asked Questions
8.1.
Why do we use getServerSideProps?
8.2.
What is returned by getServerSideProps?
8.3.
What parameters does getServerSideProps() accept?
9.
Conclusion
Last Updated: Mar 31, 2024
Medium

Server-Side Rendering in Next.JS Using getServerSideProps

Author Aditya Kumar
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

The Static Site Generation (SSG) functionality introduced in Next.js 9.3 is powerful, but for dynamic content, we still require Server-Side Rendering (SSR). The new life-cycle method getServerSideProps can be used to pre-render a page whose data must be obtained at request time for this purpose. This is often better than the original hybrid method of getInitialProps since we can more clearly separate the code intended for servers and clients.

Server-Side Rendering in Next.JS Using getServerSideProps

What is getServerSideProps?

This method is generally used to retrieve data each time a user submits a page request. Before transmitting the page to the client, it first retrieves the data. If the client makes a subsequent request, the data is retrieved once more. We may boost our SEO by using getServerSideProps because the data is rendered before reaching the client. Since the data is refreshed every time the user accesses the page, they may always see the most up-to-date information.

If we export the getServerSideProps (Server-Side Rendering) function from a page, Next.js will pre-render the page using the data returned by getServerSideProps on each request.

export async function getServerSideProps(context) {
  return {
    props: {}, // it will be provided as props to the page component
  }
}
You can also try this code with Online Javascript Compiler
Run Code

When is getServerSideProps executed?

getServerSideProps is a server-side function that never runs in the browser. If a page uses getServerSideProps, the following will happen:

  • When we access this page directly, getServerSideProps is called at request time, and the resulting props are used to pre-render the page.
  • Next.js sends an API (Application Programming Interface) call to the server, which runs getServerSideProps; when we access this page on the client-side page transitions through next/link or next/router.
  • The result of calling getServerSideProps is then returned in JSON (JavaScript Object Notation), utilised to render the page. All of this will be handled automatically by Next.js, so as long as we have getServerSideProps specified, we won't have to do anything else.
  • To see what Next.js removes from the client-side bundle, we will use the next-code-elimination tool.
  • The only way to export getServerSideProps is from a page. It is not possible to ship it from non-page files.
  • It is important to note that getServerSideProps must be exported as a standalone function; it won't work if we make it a page component property.

When should we use getServerSideProps?

getServerSideProps should only be used if you need to pre-render a page with data fetched at request time. Since the server must compute the result on every request, and the result can only be cached by a CDN using cache-control headers, the Time to First Byte (TTFB) will be higher than getStaticProps (which could require extra configuration).

If we don't need to pre-render the data, getting data on the client-side is a good option.

Behavior

In Next.js, getServerSideProps defines the behavior of fetching data on the server-side before rendering a page. It allows developers to customize data retrieval based on incoming requests, ensuring dynamic content for each page load.

Error Handling

With getServerSideProps in Next.js, developers can implement error handling logic to gracefully manage exceptions during data fetching. This ensures that even if data fetching fails, the application can respond appropriately, preventing crashes and providing a better user experience.

Edge Cases

In the context of getServerSideProps, edge cases refer to scenarios that may occur during data fetching or page rendering that are not typical or expected. Handling edge cases involves anticipating and addressing unusual conditions to ensure the robustness and reliability of the application.

Edge Runtime

The edge runtime in Next.js pertains to the execution environment where the server-side code, including getServerSideProps, runs. It encompasses the server infrastructure and configurations that determine how server-side rendering and data fetching are performed.

Caching with Server-Side Rendering (SSR)

Next.js provides caching mechanisms for server-side rendering (SSR) using getServerSideProps. By caching data fetched during SSR, Next.js optimizes performance by reducing redundant data requests and improving response times, resulting in faster page loads and improved scalability. This caching strategy enhances the efficiency and reliability of SSR in Next.js applications.

Understanding the distinction between client-side and server-side render applications

Some of the fundamental differences between server-side render and client-side render programmes are highlighted in the following sections.

1. When a user requests a web page via server-side rendering, the server generates an HTML page by retrieving user-specific data and sending it to the user's system. When it comes to client-side rendering, however, JavaScript is used to render the content in the browser. As a result, the material isn't entirely derived from an HTML document in this scenario - instead, a fundamental HTML document with a JavaScript file loads in the background.

2. This is best understood by looking at the web application's page code and then analysing it in an HTML format for further clarity.

3. Client-side rendering allows users to create sophisticated site interactions, whilst server-side rendering improves SEO (Search Engine Optimization).

4. Server-side rendered applications have a quick page load time. Once the initial load is complete, the subsequent website rendering is fast in client-side generated web applications.

5. For static pages, server-side rendering is generally recommended. When it comes to web applications, client-side rendering is the preferred method. Furthermore, client-side rendering gives you access to many JavaScript libraries.

Drawbacks

  • Client-side rendered applications are frowned upon for poor SEO performance, but server-side generated applications are infamous for encountering many server requests.
  • In server-side rendering, the entire page rendering is somewhat slow. In most circumstances, client-side rendering necessitates the use of an external library.

API Routes or getServerSideProps

When you need to receive data from the server, it's tempting to use an API Route and then call that API route from getServerSideProps. This is an inefficient and needless technique, as it will result in an additional request due to the server's getServerSideProps and API Routes executing.

Consider the following scenario. 

To get data from a CMS, an API route is used. ‘getServerSideProps’ then calls that API route directly. This results in an extra call, lowering the performance. Instead, we will import the logic from our API Route now into getServerSideProps. This may imply using a CMS, database, or other API from getServerSideProps.

How can we use getServerSideProps to get data from the server?

Each time a user accesses a page, the getServerSideProps function retrieves data. Before transmitting the page to the client, it will get the data (instead of loading the page and fetching the data on the client-side). The data will be brought again if the client makes a future request.

Usage

export async function getServerSideProps(context) {
  const res = await fetch(`https://...`)
  const data = await res.json()

  if (!data) {
    return {
      notFound: true,
    }
  }

  return {
    props: {},
  }
}

Advantages

  • Each time a client loads the page, the data is refreshed, ensuring that it is current at the time of their visit.
  • Before it reaches the customer, the data is rendered, which is helpful for SEO.

Example Usage

getServerSideProps is ideal for creating an application that requires the client to see the most up-to-date information but does not require the client to refresh the page while they are on it (we can see the client-side for constantly updating the data). For example, if we had a page on the website that displays information about the most recent GitHub commit or current Dev.to analytics, we'd want these to be fetched every time the page was seen.

Example

import NextLink from "next/link";
import { Link, Flex, Box, Text, SimpleGrid, Heading } from "@chakra-ui/core";
import { GetServerSideProps, NextPage } from "next";
import fetch from "node-fetch";
import ErrorPage from "next/error";

type Data = {
  id: string;
  name: string;
  email: string;
};

const UserPage: NextPage<{ data: Data }> = props => {
  if (!props.data) {
    return <ErrorPage statusCode={404} />;
  }

  return (
    <Box>
      <Flex flexDirection="column" alignItems="center">
        <Heading marginY="2rem">User</Heading>
        <SimpleGrid columns={2} width="2xs" spacingY={4}>
          <Text fontWeight="bold" marginRight={4}>
            UserID
          </Text>
          <Text>{props.data.id}</Text>

          <Text fontWeight="bold" marginRight={4}>
            Name
          </Text>
          <Text>{props.data.name}</Text>

          <Text fontWeight="bold" marginRight={4}>
            Email
          </Text>
          <Text>{props.data.email}</Text>
        </SimpleGrid>
        <NextLink href="/">
          <Link marginY="2rem">
            <Text fontStyle="italic">Go back home</Text>
          </Link>
        </NextLink>
      </Flex>
    </Box>
  );
};

export const getServerSideProps: GetServerSideProps = async ({
  params,
  res
}) => {
  try {
    const { id } = params;
    const result = await fetch(`http://localhost:3000/api/user/${id}`);
    const data: Data = await result.json();

    return {
      props: { data }
    };
  } catch {
    res.statusCode = 404;
    return {
      props: {}
    };
  }
};

export default UserPage;
You can also try this code with Online Javascript Compiler
Run Code

Output:

Login Page

Frequently Asked Questions

Why do we use getServerSideProps?

The Static Site Generation (SSG) functionality was to Use the next-code-elimination tool which was introduced in Next. js 9.3 is powerful, but we still require Server-Side Rendering (SSR) for dynamic content on the fly. The new life-cycle method getServerSideProps can be used to pre-render a page whose data must be obtained at request time for this purpose.

What is returned by getServerSideProps?

  • props: A serializable object supplied to the page component as an option.

return { props: { users } }

  • notFound: This method returns a 404 error and a page.

return { notFound: true,}

  • redirect: This is a redirect that allows you to go to either internal or external resources. The pattern should be { destination: string, permanent: boolean }.

return { redirect: { destination: '/post', permanent: false, },}

The getServerSideProps() method is demonstrated below with various parameters and return objects.

export async function getServerSideProps({params,req,res,query,preview,previewData,resolvedUrl,locale,locales,defaultLocale}) {

    if (query.text) {

      return { redirect: { destination: '/post', permanent: false, },}

    }

    const data = await fetch('https://jsonplaceholder.typicode.com/users');

    const users = await data.json();

    if (!data) {

    return {notFound: true,}

    }  

    return { props: { users } }

  }

 

What parameters does getServerSideProps() accept?

Let's take a closer look at the getServerSideProps() method and its parameters.

export async function getServerSideProps(context) {

  return { props: {},}

}

There are various parameters in getServerSideProps() that accept arguments.

  • params: Params contain route parameters or path variables if the page is a dynamic route.
  • req: The object of the HTTP request. 
  • res: The object of the HTTP response.
  • query: The query string is represented by an object. For example, path.text can obtain text=search from a URL.
  • preview: Whether the page is in preview mode or not determines whether it is true or false.
  • previewData: setPreviewData creates the data.
  • resolvedUrl: Original query values with the normalised request URL
  • locale: Contains the active locale if enabled.
  • locales: Contains all supported locales if enabled.
  • defaultLocale: Contains the configured default locale if enabled.

Conclusion

In this article, we have seen the uses of getServerSideProps and how it is useful. We have seen the benefits of using it and how it helps fetch data from an API. We have discussed its return types and what it takes as an argument. We learned how to utilise getServerSideProps to dynamically fetch data and server-side render pages in our project by consuming a "user profile" API route.

If you want to learn more about next.js, you can check here Introduction to Next.js.

To know more about popular web technologies, check out this article

If you are eager to learn advanced front-end web development, Coding Ninjas is here with one of the best courses available, which you can find here.

Do check out The Interview guide for Product Based Companies as well as some of the Popular Interview Problems from Top companies like Amazon, Adobe, Google, etc. on Coding Ninjas Studio.

Also check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, etc. as well as some Contests, Test Series, Interview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.

Happy Learning!

Live masterclass