How to Get Current Route in Next.js
If you want to get the current route in a Next.js project, use the useRouter
hook. It contains properties such as pathname
, query
and asPath
that describe current route.
The best way I’ve found to get current route inside a component is to use asPath
property from userRouter
.
import { useRouter } from 'next/router';
export default function Component() {
const { asPath } = useRouter();
return </>
}
It is best to use asPath
because it returns the exact route that the browser displays. Unlike pathname
that doesn’t work with dynamic routes, because it doesn’t fill the dynamic route segment.
import { useRouter } from 'next/router';
const { pathname } = useRouter();
console.log(pathname);
This will produce output the following.
/posts/[slug]
There is problem getting the exact URL with asPath
though. The issue is that asPath
also includes URL fragments and query parameters.
If your user lands on a page with a URL https://your-website.com/posts/#main?filter=1
, then asPath
will return the following string.
/posts/#main?filter=1
To strip away the unnecessary parts and get a clean URL, you can do the following.
const { asPath } = useRouter();
const cleanPath = asPath.split('#')[0].split('?')[0];
Now you can use the clean URL to, for example, in meta tags inside your SEO component.
<meta property="og:url" content={`https://your-website.com/${cleanPath}`} />