NextJS best practice for handling "Server Error" and "Client side error"
One of the best practices to handle errors is use Early Return, by returning a statusCode
prop inside of the getInitialProps and use that statusCode
to render the error page after render the page to prevent handle the posible errors inside the page.
- If everything is ok 200
- If does not exist 404
- If server error 503
import Error from "next/error"function Page({ stars, statusCode}) { if(statusCode !== 200) { <Error statusCode={statusCode} /> } return <div>Next stars: {stars}</div>}Page.getInitialProps = async (ctx) => { try{ const res = await fetch('https://api.github.com/repos/vercel/next.js') const json = await res.json() if(res.status >= 400){ return { stars: json.stargazers_count, statusCode: res.status } } return { stars: json.stargazers_count, statusCode: 200 } } catch(error){ return {stars: null, statusCode: 503} } }export default Page