How to create a custom 503 service unavailable page in Next.js



Image not found!!

To create a custom 503 service unavailable page in Next.js, you can follow these steps:

  1. Create a Custom Error Page: First, create a new page under the pages directory in your Next.js project. You can name it 503.js or any other name you prefer.

    javascript
    // pages/503.js const ServiceUnavailable = () => { return ( <div> <h1>503 Service Unavailable</h1> <p>Sorry, the service is currently unavailable. Please try again later.</p> </div> ); }; export default ServiceUnavailable;
  2. Handle the Error in _app.js (Optional): If you want to handle 503 errors globally, you can do it in the _app.js file.

    javascript
    // pages/_app.js import { useEffect } from 'react'; import { useRouter } from 'next/router'; const App = ({ Component, pageProps }) => { const router = useRouter(); useEffect(() => { const handleRouteChange = (url) => { console.log('Route change', url); // Handle route change here }; router.events.on('routeChangeStart', handleRouteChange); return () => { router.events.off('routeChangeStart', handleRouteChange); }; }, [router]); return <Component {...pageProps} />; }; export default App;
  3. Customize Error Handling (Optional): If you need to handle 503 errors in a specific way (e.g., logging, redirecting), you can customize the error handling in the _error.js file.

    javascript
    // pages/_error.js const ErrorPage = ({ statusCode }) => { return ( <div> <h1>{statusCode} - Service Unavailable</h1> <p>Sorry, the service is currently unavailable. Please try again later.</p> </div> ); }; ErrorPage.getInitialProps = ({ res, err }) => { const statusCode = res ? res.statusCode : err ? err.statusCode : 503; return { statusCode }; }; export default ErrorPage;
  4. Configure Custom Error Handling (Optional): You can configure custom error handling by modifying the pages/_error.js file as needed.

    javascript
    // pages/_error.js import { useEffect } from 'react'; import Router from 'next/router'; const ErrorPage = ({ statusCode }) => { useEffect(() => { // Custom error handling logic here }, []); return ( <div> <h1>{statusCode} - Service Unavailable</h1> <p>Sorry, the service is currently unavailable. Please try again later.</p> </div> ); }; ErrorPage.getInitialProps = ({ res, err }) => { const statusCode = res ? res.statusCode : err ? err.statusCode : 503; return { statusCode }; }; export default ErrorPage;
  5. Customizing Styles (Optional): You can customize the styles of your custom error page by adding CSS or using a CSS-in-JS solution like styled-components.

  6. Testing: Test your custom 503 service unavailable page by deliberately causing a 503 error, either by temporarily shutting down your server or by returning a 503 status code from your server-side logic.

By following these steps, you can create a custom 503 service unavailable page in Next.js and customize its behavior according to your requirements.