In Next.js, you can use the useRouter
hook from the next/router
module to access the current URL and its properties, including the pathname, query parameters, and other information. Here's an example of how you can use the useRouter
hook to get the current URL:
next/router
module installed. If not, you can install it using:bashnpm install next/router
# or
yarn add next/router
useRouter
hook:jsximport { useRouter } from 'next/router';
useRouter
hook in your component to access the current URL and its properties:jsximport { useRouter } from 'next/router';
function MyComponent() {
const router = useRouter();
// Accessing the pathname
const currentPath = router.pathname;
// Accessing the query parameters
const { query } = router;
// Accessing the entire URL
const currentUrl = typeof window !== 'undefined' ? window.location.href : '';
return (
<div>
<p>Current Path: {currentPath}</p>
<p>Query Parameters: {JSON.stringify(query)}</p>
<p>Current URL: {currentUrl}</p>
</div>
);
}
export default MyComponent;
This example demonstrates how to use the useRouter
hook to get the current pathname, query parameters, and the entire URL. Note the check for typeof window !== 'undefined'
before accessing window.location.href
to ensure that the code only runs on the client side (not during server-side rendering).
Keep in mind that this code should be used within components rendered on the client side. If you need to access the router object in a different context (e.g., inside an API route or a utility function), you might want to explore other options such as passing the router object as an argument.