1

I have a Next.js app with three routes: /home, /about, and /contact.

If a user lands on a route that doesn't exist, by default, Next.js will direct them to the 404 page.

However, I want to avoid redirecting them to the 404 page. Instead, I'd like to establish a permanent redirection to /home. This means that if someone lands on an unavailable route, they will automatically be redirected to /home.

I need to set this up from the server side in the Next.js config file. The reason for this is that I recently acquired a domain, and users are currently hitting a lot of 404 pages for URLs that used to be live. I want to minimize the number of users encountering 404 errors.

While it's relatively straightforward to implement this when we know the specific unknown page a user might land on, without knowing the exact routes, we'll likely need to use a regex pattern. Unfortunately, I'm struggling to figure out how to do this.

Could you please provide guidance on potential solutions or approaches to achieve this?

1 Answer 1

0

You could export a custom 404 page and redirect users to your home page.

export default function Custom404() {
  const router = useRouter();
  useEffect(() => router.push('/home'), [router])
  return <h1>Oops! We didn't find this page. We'll redirect you to home page</h1>
}

Users will still show a 404 page but I don't think it's a good idea to avoid this. Users have to know that the requested url doesn't exist. You'd better understand why so many users lands on this page.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes, we can do it. However, the main issue is that I want to respond to unknown routes with a permanent redirection to /home. Adding useEffect in the 404 page will still result in a lot of 404 requests.
You cannot do that, except by defining ALL unexisting routes in the redirect function of next.config.js. Otherwise, user request will always try to reach a resource on the server that doesn't exist, and you cannot avoid that. 404 page does exist for a reason. But I don't think next.config.js provides a catch all route.
You can perform redirection on server side tho, but tout users will still reach 404.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.