Next.js getServerSideProps() Function
Last Updated :
25 Sep, 2024
The getServerSideProps method is used to fetch data and pre-render the page. It enables server-side rendering. As a result, it's particularly useful for sites with dynamic data or requests that must be made often, such as retrieving authorized user data.
Syntax:
export async function getServerSideProps(context) {
return {
props: {},
}
}
Parameter:
It accepts the context object which can have the following properties:
- params: If this page utilizes a dynamic route, the route parameters are stored in params. If the page's name is [id].js, the parameters will be { id: ... }
- req: The HTTP IncomingMessage object.
- res: The HTTP response object.
- query: An object for the query string.
- preview (boolean): If the page is in Preview Mode, preview is true; otherwise, it is false.
- previewData: The preview data set by setPreviewData.
- resolvedUrl: A normalized version of the request URL in which the _next/data prefix is removed for client transitions, and the original query values are included.
- locale: Contains the active locale (if enabled).
- locales: Contains all supported locales (if enabled).
- defaultLocale: The configured default locale.
Returns:
An object containing any of the following properties is returned by the getServerSideProps function:
- props: The props object is a key-value pair in which the page component receives each value. It should be a serializable object that can be serialized using JSON.stringify.
- notFound: The page can return a 404 status and 404 Page if the notFound boolean is true. The page will return a 404 if notFound is true, even if the page was previously properly produced.
- redirect: The redirect object enables internal and external resource redirection. It needs to be the same shape as { destination: string, permanent: boolean }. In some unusual circumstances, a special status code may be required to appropriately redirect older HTTP clients. You can use the statusCode property instead of the permanent property in certain circumstances, but not both.
Steps to SetUp Next Project
To run the examples given ahead, you will need to create a Next.js project. For the purposes of demonstration, I have created a project named test-project. You can do so by typing the following command:
Step 1: Create a project folder and move into it by using the below command in the terminal:
mkdir foldername
cd foldername
Step 2: In that foldername, create your project by using the below command in the terminal:
npx create-next-app test-project
Step 3: Create two additional files namely about.js and home.js in the pages directory for the examples
Project Structure:
This project should look like this:
Steps to run the application: To run the server in development mode, you will need to type the following command:
npm run dev
Note: By default, it will start the server on port 3000, however, if the port is already in use it will choose the first port which is free starting from 3001.
Example 1: Type the following code in pages/about.js. You can visit localhost:3000/about to view the output.
JavaScript
// Filename - about.js
export default function About({ message }) {
return (
<div>
<h1>{message}</h1>
</div>
);
}
export function getServerSideProps() {
return {
props: { message: "Welcome to the About Page" },
};
}
Output:
Example 2: Type the following code in pages/home.js. You can visit localhost:3000/home to view the output.
JavaScript
// Filename - home.js
export default function Home({ message }) {
return (
<div>
<h1>This is Home Page</h1>
<h2>{message}</h2>
</div>
);
}
export function getServerSideProps() {
return {
notFound: true
};
}
Output:
Reference: https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props
Similar Reads
Next.js getStaticProps() Function Data fetching in NextJS: To fetch the data from our own backend or using third-party APIs, we generally use client-side fetching using the fetch API provided by the browser. It fetches the data from the client-side on every request or browser reload. Â But NextJS provides us with better ways to fetch
3 min read
Next.js getStaticPaths() Function The getStaticPaths() function in NextJS is used to pre-generate static pages for dynamic routes.For example, we can create a page that has dynamic parameters like `user/[ID]` Â and then we can create a static version for every possible value of the dynamic parameter. In our case, if the dynamic param
3 min read
Functions in Next JS Next.js provides a suite of functions and hooks that enhance server-side rendering, static generation, routing, and more. These functions are essential for managing data fetching, handling requests, and optimizing performance in Next.js applications.Next.js FunctionsNext.js functions simplify server
4 min read
p5.js getURLParams() Function The getURLParams() function is used to return the current URL parameters a JavaScript object, with each parameter as a separate member of the object. Syntax: getURLParams() Parameters: This function does not accept any parameters. Return Value: It returns an Object of the path parameters. Below exam
1 min read
Next.js getInitialProps getInitialProps is a special function provided by Next.js that runs on the server side before rendering a page. This function allows you to fetch data from an external API, database, or any other data source, and pass it as props to your React components. By doing so, you can pre-populate your pages
5 min read