Confessions and Confusions of Ashok M A. Personal and Professional Blog.

Ashok Mannolu Arunachalam, How toNextJSJSReact routingError handling

How to redirect on 404 error in Next JS

I have recently migrated my blog to NextJS. I read great things about it when it comes to Search Engine Optimization(SEO) and static site generation (SSG).

I will be sharing my journey towards JAMSTACK. In this case, towards NextJS.

I am trying to make use of it in the best possible way.

Case problem

I have already migrated this blog to NextJS and made my cloudflare site point to this page. But, the Google Search Console has already some indexed urls such as

If you are lucky, you can see it in the results for this search query.

After migration, the above link was showing 404 page of NextJS. It makes total sense but not at all good for my organic traffic. T_T


Introduced custom 404 by extending the default <Error /> from next/error. The fix is simple with useRouter.

export default function FourOh4() {
const router = useRouter()
const path = router.asPath
.filter((s) => !!s)
if (path.length > 1) {
return null
} else {
return (
<Error statusCode={404} />
<Footer className="mx-64" />

It is a quick work around but it is effective. Most of the organic traffic, still comes from the already indexed pages. I have enabled NextJS blog since midnight of .

Google Search Console will eventually catch up and update it's indices. Until then, I am going to keep this up and create respectie redirect pages after monitoring the traffic for sometime.

Do not be like me and learn from my mistakes. T_T

First of all create respective pages (either direct or wildcard) in NextJS with proper redirect code such as 301 Moved Permanently.

This will let crawlers and bots know that resource is present and traffic is valid. Only that the resource has been moved to a different location.