Dynamic routing in Next.js is a powerful feature that allows developers to create pages with dynamic content based on the URL. This is particularly useful for applications that need to display different data based on user input or other variables. In Next.js, dynamic routes are created using file-based routing, where the file names in the `pages` directory dictate the routes of the application.
To implement dynamic routes, Next.js uses square brackets in the file names to indicate dynamic segments. For example, if you want to create a route for user profiles based on their ID, you would create a file named `[id].js` inside the `pages/users` directory. This setup allows Next.js to match any URL that follows the pattern `/users/[id]` and render the corresponding page.
To create a dynamic route, follow these steps:
Here’s an example of how to set up a dynamic route for user profiles:
import { useRouter } from 'next/router';
const UserProfile = () => {
const router = useRouter();
const { id } = router.query; // Access the dynamic parameter
return (
User Profile
User ID: {id}
);
};
export default UserProfile;
When working with dynamic routes, you often need to fetch data based on the dynamic parameter. Next.js provides two methods for data fetching: `getStaticProps` for static generation and `getServerSideProps` for server-side rendering.
If you know the possible values for the dynamic parameter at build time, you can use `getStaticProps` along with `getStaticPaths` to pre-render pages:
export async function getStaticPaths() {
const users = await fetch('https://api.example.com/users');
const paths = users.map(user => ({ params: { id: user.id.toString() } }));
return { paths, fallback: false }; // Set fallback to false for 404 on unknown paths
}
export async function getStaticProps({ params }) {
const user = await fetch(`https://api.example.com/users/${params.id}`);
return { props: { user } };
}
If the data needs to be fetched at request time, use `getServerSideProps`:
export async function getServerSideProps({ params }) {
const user = await fetch(`https://api.example.com/users/${params.id}`);
return { props: { user } };
}
By following these guidelines, you can effectively implement dynamic routes in your Next.js applications, providing a seamless experience for users while maintaining clean and efficient code.