I have a custom 500 error page called 500.tsx and I want to able to show this page when request from client fails with status of 500, but keeping client on old url (for example /auth/register). I have a axios listener on error which should do all the work. But could not find a way to do this using next/router. Any help appreciated
Didn't realize OP wanted to show 500 page at first.
You could look into router.isFallback but I am not entirely sure if that's appropriate for this.
It's supposed to be for Page Loading Indicators, but in your case, since the page will never load, it could work.
https://nextjs.org/docs/basic-features/data-fetching#fallback-true
return router?.isFallback
? <Custom500Page/>
: <RegularPage/>
You can set this variable from getStaticPaths method, which runs during build time and is usually used for [slug] pages.
// This function gets called at build time
export async function getStaticPaths() {
// Fetch paths to your slug pages here
return {
// paths,
fallback: true
}
}
Showing 404 page is quite straight forward & This is how we do.
You can conditionally export a variable called notFound as true from getStaticProps method.
If the URL is invalid and you don't data to render the page, you simply pass that notFound prop as true and then the default or custom 404 page will show up automatically preserving your invalid url.
// This function gets called at build time
export async function getStaticProps({ params, preview = false }) {
let pageData
try {
// fetch pageData from API here
} catch (error) {
// catch errors
}
// check validity or emptyness of data
// invalid URL (slug) -> empty data from API
// valid URL (slug) -> valid data from API
return isObjectEmpty(pageData)
? { notFound: true }
: {
props: {
pageData
// pass other props to the page
}
}
}
NextJS Docs on getStaticProps & not-found
https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation