How to use getInitialProps In Next.js
In Next.js, the getInitialProps method is utilized within page components to fetch data and pass it as props before rendering, essential for server-side rendering and pre-rendering pages. It enables data fetching from APIs, server-side rendering, SEO enhancement, and dynamic content generation by handling query parameters efficiently.
Example: Implementation to show how to get query parameters from the URL using getInitialProps.
//index.js
import Head from "next/head";
function Home({ param1, param2 }) {
// Access param1 and param2 here
// For example:
const paramsdata =
`Param1: ${param1}, Param2: ${param2}`;
return (
<>
<Head>
<title>Create Next App</title>
</Head>
<main style={{ height: "100vh" }}>
<p>{paramsdata}</p>
</main>
</>
);
}
Home.getInitialProps = async ({ query }) => {
// Access query parameters from query object
const { param1, param2 } = query;
// Fetch data based on query parameters
// Return data as props
return { param1, param2 };
};
export default Home;
Output:
How to Get Query Parameters from URL in Next.js?
Next.js, a popular React framework, provides powerful features for building server-side rendered (SSR) and statically generated (SSG) applications. Handling query parameters becomes essential when working with dynamic routes and user interactions. This article will explore how to efficiently extract and manage query parameters from the URL in Next.js applications.