In Next.js, accessing URL parameters on the server side is primarily handled within the getServerSideProps or getInitialProps functions of the page. These functions run on the server side and can access the complete request information, including query parameters.
Using getServerSideProps
Definition
getServerSideProps is an asynchronous function that executes on every page request to fetch necessary data from the server before rendering. This function can access all parameters from the request, including URL query parameters.
Example
Suppose you have a page with a URL such as /products?category=shoes, and you want to retrieve the category parameter on the server side to fetch data from a database or API based on it.
jsx// pages/products.js export async function getServerSideProps(context) { // Access URL parameters from context.params or context.query const { query } = context; const { category } = query; // Assume we fetch product data from an API based on category const products = await fetchProductsByCategory(category); // The returned props will be passed to the React component return { props: { products, }, }; } function Products({ products }) { return ( <div> <h1>Products</h1> {products.map(product => ( <div key={product.id}>{product.name}</div> ))} </div> ); } export default Products;
In the above example, the getServerSideProps function accesses the URL query parameter category via context.query and then uses this parameter to fetch the corresponding product data.
Using getInitialProps
Definition
getInitialProps is an older feature in Next.js that allows you to fetch data on either the server side or client side, depending on the request type. It can also accept a context object containing the URL query parameters.
Example
Here is an example of accessing URL parameters when using getInitialProps:
jsx// pages/products.js Products.getInitialProps = async (ctx) => { // ctx.query contains all URL query parameters const { category } = ctx.query; // Fetch product data based on category const products = await fetchProductsByCategory(category); return { products }; }; function Products({ products }) { return ( <div> <h1>Products</h1> {products.map(product => ( <div key={product.id}>{product.name}</div> ))} </div> ); } export default Products;
Summary
In Next.js, whether you use getServerSideProps or getInitialProps, you can conveniently access and use URL parameters on the server side for data fetching or other operations. This is highly beneficial for building server-side rendered applications, significantly improving performance and user experience.