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 https://ashokma.com/2019/02/18/install-nodejs-and-npm-pop-os/.
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
Solution
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.trim().split('/').filter((s) => !!s)if (path.length > 1) {router.push(`/posts/${path.pop()}`)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.