Dynamic Route Matching in Next.js 14
Showcase how to create a dynamic route with a catch-all parameter and retrieve query parameters server-side in getServerSideProps.
import { useRouter } from 'next/router';
export default function CatchAllPage() {
const router = useRouter();
const { params = [] } = router.query; // 'params' is an array containing the catch-all route segments
return (
<div>
<h1>Catch All Route</h1>
<p>Query parameters: {JSON.stringify(params)}</p>
</div>
);
}
This component showcases a catch-all dynamic route in Next.js. It uses the useRouter hook from Next.js to access the query parameters, which includes the catch-all parameters under the key 'params'. The parameters are then displayed on the page.
export async function getServerSideProps(context) {
// context.params will contain the catch-all parameters as an array
const { params } = context;
// Implement data fetching or other server-side logic here, using the catch-all parameters if needed
return {
props: { }, // pass fetched data to the page component as props
};
}
This function is part of the same file as the CatchAllPage component. getServerSideProps is used for server-side rendering in Next.js. It retrieves the catch-all parameters from the context object provided by Next.js. You can then perform any server-side operations such as data fetching with the parameters and pass the result to the component as props.
[...params].js
This filename indicates a catch-all dynamic route in the /pages directory of a Next.js project. The three dots (...) before params mean that all segments of the route after a certain path will be caught and passed as an array to the params key in the query object. Place this file inside a folder structure that defines the static part of your dynamic route, for example /pages/products/[...params].js for a route like /products/foo/bar.