While Next.js excels at declarative routing using its file-based system, there are many scenarios where you'll need to navigate programmatically within your application. This could be after a successful form submission, when a user clicks a specific button, or based on certain application logic. Next.js provides the next/router module to handle these programmatic navigation needs.
The core of programmatic navigation in Next.js lies within the useRouter hook. This hook provides access to the router object, which contains methods for manipulating the browser's URL and controlling navigation. You can use useRouter within any functional component.
import { useRouter } from 'next/router';
function MyComponent() {
const router = useRouter();
// ... rest of your component
}The router object exposed by useRouter has several key methods for navigation. The most common are push and replace.
router.push(url, as, options): This method pushes a new URL onto the browser's history stack. This means the user can navigate back to the previous page using the browser's back button. The url argument is the actual path to navigate to, and as (optional) is for URL masking (e.g., displaying a pretty URL while internally navigating to a different one). The options object can include scroll: false to prevent scrolling to the top of the new page.
import { useRouter } from 'next/router';
function NavigationButton() {
const router = useRouter();
const handleClick = () => {
router.push('/about');
};
return <button onClick={handleClick}>Go to About Page</button>;
}router.replace(url, as, options): This method replaces the current entry in the browser's history stack with the new URL. This is useful for scenarios like redirects after login, where you don't want the user to be able to go back to the login page after they've been authenticated. The arguments are similar to push.