TIP&HACK

WordPress Tips – Troubleshooting and Maintenance : Customizing your 404 error page

Customizing your 404 error page

A 404 error page is shown to users who visit a wrong path on a website. In Next.js, you can easily customize this page to provide a more user-friendly environment.

advertisement
advertisement

Creating a Custom 404 Page in Next.js

To create a custom 404 page in Next.js, add a 404.js or 404.tsx file in the pages directory of your project.

Example Code

Here is a simple example of creating a custom 404 page:

// pages/404.js
import Header from '../components/Header';
import Footer from '../components/Footer';

export default function Custom404() {
  return (
    <>
      <Header />
      <h1>Custom 404 Error Page</h1>
      <p>The page you are looking for does not exist.</p>
      <Footer />
    </>
  );
}

This file is automatically delivered by Next.js when a user navigates to a non-existent page.

Customizing 404 and 500 Error Pages

404 Error Page

  • Create a 404.js file in the pages directory to handle 404 errors. This page is usually static and customizable as needed.

500 Error Page

  • To handle server-side errors (500 errors), you should create a _error.js file in the pages directory. This file handles server-side errors and can be customized to display relevant error messages.
// pages/_error.js
function Error({ statusCode }) {
  return (
    <p>
      {statusCode
        ? `An error ${statusCode} occurred on server`
        : 'An error occurred on client'}
    </p>
  );
}

Error.getInitialProps = ({ res, err }) => {
  const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
  return { statusCode };
};

export default Error;

This approach ensures different handling for server-side and client-side errors.

Best Practices for Managing 404 Errors

Client-Side Solutions

  • URL Validation: Ensure the URL is correct and free of typos.
  • Browser Cache: Clear the browser cache and cookies to ensure they do not interfere with the data being provided.
  • User-Friendly 404 Page: Provide a helpful and friendly 404 page with messages and links to the homepage or other relevant pages.

Server-Side Solutions

  • Server Log Analysis: Analyze server logs to identify the source of 404 errors and amend incorrect links or URL configurations.
  • Redirection Setup: Set up redirections for moved or renamed pages to prevent 404 errors.
  • CDN and Caching Setup: Ensure CDN and cache settings do not deliver incorrect resources.

SEO Considerations

  • Use Google Search Console: Use Google Search Console to detect and repair 404 errors to prevent negative impacts on SEO.
  • XML Sitemap: Update the XML sitemap to include only valid URLs.
  • Broken Link Checker: Use tools to detect and fix broken links on the site.

By following these steps and best practices, you can effectively customize and manage 404 error pages in Next.js, enhancing user experience and SEO.

Copied title and URL