In Next.js, getInitialProps is an asynchronous function that allows you to access nearly all initialization data, including the context object (context), which contains various properties such as query and params. If you need to retrieve query parameters from the URL, you can access them via context.query.
Here is an example of a getInitialProps function demonstrating how to retrieve query parameters from the URL:
jsximport React from 'react'; const MyPage = ({ queryParam }) => { // Use the query parameter in the page return ( <div> <p>The value of the query parameter is: {queryParam}</p> </div> ); }; MyPage.getInitialProps = async (ctx) => { // ctx.query contains all query parameters const { query } = ctx; // Assuming your URL is "/my-page?search=nextjs", you can access the 'search' query parameter value via query.search const queryParam = query.search; // The returned object will be passed as props to the page component return { queryParam }; }; export default MyPage;
In the above example, we assume your page URL is "/my-page?search=nextjs". By using ctx.query, you can retrieve the value of the search query parameter and pass it as queryParam to the MyPage component.
It's worth noting that starting from Next.js 9.3, the official recommendation is to use getStaticProps and getServerSideProps instead of getInitialProps, as these new data fetching methods better integrate with Next.js's Static Generation and Server-Side Rendering features. If your page requires data to be fetched at request time, you should use getServerSideProps. If the query parameters change dynamically between the user's browser and the server, you can use the Router or useRouter hook on the client side to retrieve them.