James Whiteley
James Whiteley

Reputation: 3474

How do I access the current route on a Next.JS custom 404 page?

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>
  );
};

Upvotes: 8

Views: 5906

Answers (3)

ffx292
ffx292

Reputation: 711

Old question but just adding onto this if you're using Next.js 13

Instead of using router.asPath, you need to import usePathname from next/navigation

Eg.

'use client';

import { usePathname } from 'next/navigation';

const NotFoundPage = (): JSX.Element => {
    return (
        <div>
           {usePathname()} not found
        </div>
    );
};

export default NotFoundPage;

Upvotes: 1

Wojciech Maj
Wojciech Maj

Reputation: 1122

You can access the original route by accessing router.asPath, where router is returned from useRouter() hook. Beware though, if you don't specify getStaticProps, router.asPath will return "/404" on server side, causing hydration error.

So to make use of router.asPath you will have to create getStaticProps function that doesn't return anything

import { useRouter } from 'next/router';

import type { GetStaticProps } from 'next';

type Props = Record<string, never>;

export const getStaticProps: GetStaticProps<Props> = () => {
  return { props: {} };
};

export default function PageNotFound() {
  const router = useRouter();

  return (
    <p>
      The requested page <strong>{router.asPath}</strong> could not be found.
    </p>
  );
}

Upvotes: 4

Sinan Yaman
Sinan Yaman

Reputation: 5946

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>
  );
};

Upvotes: 6

Related Questions