-
We are looking at build portions of our site with Next.js/React. What is the best way to redirect all 404s to another link that might be external. So far it looks like can only do a useEffect with window.location to the different 404 link. But this doesn't cover all 404s. I tried using the rewrites and it has a proxy error (included the error for a bogus url, but happens for my domain as well), plus all 404s are not routed through this, only anytime the /404 is used.
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I was able to solve this by using the latest canary version as well as the experimental feature but instead of rewrites, using redirects: experimental: {
redirects() {
return [{ source: '/error404', destination: 'http://www.sample.com/404.html', permanent: true }];
},
},
}; Then I created the _error.js to do a router push to /error404 based on the sample code from the docs and a few of the comments for doing the redirect. import { useEffect } from 'react';
import { useRouter } from 'next/router';
function Error({ statusCode }) {
console.log('Error - Error Component');
const router = useRouter();
useEffect(() => {
router.push(`/error404`);
});
return '';
}
Error.getInitialProps = ({ res, err }) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
return { statusCode };
};
export default Error; Then I created a 404.js that uses the same type of functionality as my component. In my SSG with fallback=true, I do the following in my getStaticProps and it allows me to throw the 404 when getStaticPath returns a detail page with no data. catch (err){
// Need some return statement in case a story is not found
console.log('Error in detail page getStaticProps. Unable to retrieve some of the data: ', err.message);
return {
props: {
hasNoStory: true,
},
};
} Then in my component I check for the boolean value: export default function Story({ story, hasNoStory = false }) {
if (hasNoStory) {
console.log('Error - Story Component');
Error(404);
} Tested for an hour or so and this looks like it works well. For me we are routing all errors to a 404 page that exists on our standard site and it is external to the React/NextJS app. |
Beta Was this translation helpful? Give feedback.
I was able to solve this by using the latest canary version as well as the experimental feature but instead of rewrites, using redirects:
Then I created the _error.js to do a router push to /error404 based on the sample code from the docs and a few of the comments for doing the redirect.