I have a custom 404 page in my Next.JS app (404.js). On the page, I'd like to display a message like The route <strong>/not-a-route</strong> does not exist
, however when using Next.js's useRouter()
and router.pathname
, the router thinks I'm on /404
and instead displays The route <strong>/404</strong> does not exist
. How do I access the actual route I'm on in a custom 404 page?
export const NotFound: React.FC = () => {
const router = useRouter();
console.log(router.pathname) // prints /404
return (
<Layout title='Oops! Something went wrong!'>
<div className={styles.container}>
<h1>Oops! Something went wrong!</h1>
<p>
The route <strong>{router.pathname}</strong> does not exist.
</p>
</div>
</Layout>
);
};
You can access the redirected route
as router.asPath
. Try:
import {useRouter} from 'next/router'
export const NotFound: React.FC = () => {
const router = useRouter();
console.log(router.asPath)
return (
<Layout title='Oops! Something went wrong!'>
<div className={styles.container}>
<h1>Oops! Something went wrong!</h1>
<p>
The route <strong>{router.asPath}</strong> does not exist.
</p>
</div>
</Layout>
);
};