Design Converter
Education
Developer Advocate
Last updated on Apr 29, 2024
Last updated on Apr 29, 2024
When you're navigating the web and hit a dead-end, the "404 page not found" message is a universal sign that what you were looking for doesn't exist at that URL. It's like knocking on a door and finding nobody home.
This error page serves as a digital no-man's-land, telling you that the content you hoped to find has either moved to a new location or vanished entirely.
Next.js is a React framework that provides a robust set of features to build web applications. It simplifies tasks like server-side rendering and static site generation, making it easier to create fast and SEO-friendly pages.
With Next.js, developers can enjoy the power of React along with the benefits of a more structured framework, which includes file-based routing, API routes, and built-in support for CSS and data fetching.
Routing in Next.js is based on the file system, which means that the routes of your application correspond to the file names in your ‘pages' folder. For example, a file named about.tsx in the ‘pages' folder will automatically be served at the /about URL. This convention makes it simple to set up both static routes and dynamic routes.
Dynamic routes allow you to create pages that can match a variety of URL patterns, and they're defined by adding square brackets to a file name or a dynamic route folder. For instance, a file named [id].tsx inside a folder called posts would match routes like /posts/1 or /posts/hello-world, with the part inside the brackets ([id]) being a variable.
To handle multiple dynamic routes, you can nest dynamic route folders within each other, and Next.js will automatically handle visits to these routes based on the matching route pattern. If no matching route is found, Next.js will then look for a custom 404 page to display.
When you're working with Next.js, handling errors gracefully is a key part of providing a smooth user experience. One of the most common errors a user might encounter is the dreaded 404 error, indicating that the page they're trying to reach doesn't exist. Next.js, being the user-friendly framework it is, comes equipped with a default 404 page that automatically handles such cases.
The default 404 page in Next.js is a simple, no-frills error page that gets the job done. It's designed to be functional, displaying a straightforward message that the user has hit a dead-end. The message "404 - Page Not Found" is prominently displayed, leaving no doubt about what has gone wrong.
However, while the default 404 page serves its purpose, it's quite basic and doesn't offer much beyond the error message. It doesn't include any links to redirect the user back to active parts of your site, nor does it carry over the look and feel of your application. This can be a missed opportunity to maintain engagement and guide users back on track.
Here's what the default 404 page might look like in a Next.js app:
While the default page is automatically provided by Next.js, it's important to note that you won't find a physical file in your project for this default 404 page.
Next.js handles this internally, but it gives you the option to override this page with a custom one, which is highly recommended for enhancing the user experience and keeping your site's branding consistent.
Creating a custom 404 page in Next.js is a straightforward process that can greatly improve the user experience on your site. A well-designed custom 404 page can turn the frustration of a wrong turn into an opportunity to engage with your users and help them find their way.
Let's walk through the steps to create a custom 404 page and discuss some design tips to make it effective.
To get started, you will need to create a new file named 404.js (or 404.tsx if you're using TypeScript) in your ‘pages' folder. This file will be your custom 404 page component that Next.js will automatically use whenever a page is not found.
1// pages/404.js 2import React from 'react'; 3import Link from 'next/link'; 4 5export default function Custom404() { 6 return ( 7 <div align="center"> 8 <h1>404 - Page Not Found</h1> 9 <p>It seems we can't find what you're looking for. Perhaps searching can help.</p> 10 <Link href="/"> 11 Go back home 12 </Link> 13 </div> 14 ); 15}
In the 404.js file, you will define a React component that will be rendered when a 404 error occurs. The component should return JSX that includes a message to inform the user that the page they are looking for cannot be found, and it should provide a way for them to navigate back to the main part of your site.
The message on your custom 404 page should be clear and friendly. Avoid technical jargon that might confuse users and instead offer a simple explanation that the requested page is not available. You can also use a bit of humor or a light-hearted tone if it fits with your brand's voice.
Always include links that allow users to easily navigate back to other parts of your site. This could be a link to the home page, a search bar, or links to popular content. The goal is to keep users engaged and prevent them from leaving your site out of frustration.
1// pages/404.js 2import React from 'react'; 3import Link from 'next/link'; 4 5export default function Custom404() { 6 return ( 7 <div> 8 <h1>404 - Page Not Found</h1> 9 <p>Can't find what you're looking for? Try searching:</p> 10 <input type="text" placeholder="Search..." /> 11 <Link href="/"> 12 Or go back home 13 </Link> 14 </div> 15 ); 16}
Your custom 404 page should match the look and feel of the rest of your application. Use the same CSS or styling solution that you use for other pages to maintain consistency. This helps reinforce your brand identity and makes the 404 page feel like a cohesive part of your site.
1// pages/404.js 2import React from 'react'; 3import Link from 'next/link'; 4import styles from './Custom404.module.css'; // Assuming you have CSS modules set up 5 6export default function Custom404() { 7 return ( 8 <div className={styles.errorContainer}> 9 <h1 className={styles.errorTitle}>404 - Page Not Found</h1> 10 <p className={styles.errorMessage}> 11 We're sorry, but the page you were looking for doesn't exist. 12 </p> 13 <Link className={styles.homeLink} href="/"> 14 Take me home 15 </Link> 16 </div> 17 ); 18}
1/* Custom404.module.css */ 2.errorContainer { 3 position: fixed; /* Use fixed to cover the entire viewport */ 4 top: 0; 5 left: 0; 6 right: 0; 7 bottom: 0; 8 display: flex; 9 align-items: center; /* Vertical centering */ 10 justify-content: center; /* Horizontal centering */ 11 text-align: center; 12 background-color: #f7f7f7; /* Light grey background */ 13} 14 15.errorTitle { 16 font-size: 2rem; 17 color: #333; 18 margin-bottom: 1rem; 19} 20 21.errorMessage { 22 font-size: 1rem; 23 color: #666; 24 margin-bottom: 2rem; 25} 26 27.homeLink { 28 font-size: 1rem; 29 padding: 10px 20px; 30 color: #fff; 31 background-color: #0070f3; 32 border: none; 33 border-radius: 5px; 34 text-decoration: none; 35 transition: background-color 0.3s ease; 36} 37 38.homeLink:hover { 39 background-color: #0056b3; 40}
Once you have a basic custom 404 page in place, you can enhance it by adding interactivity and utilizing various Next.js features. These enhancements can make the page more helpful and engaging for users who land on it. Let's explore how to add these features to your custom 404 page.
A search bar can be a valuable addition to your 404 page, allowing users to quickly search for the content they were originally looking for. Implementing a search bar will require a text input for the search query and a button to submit the search. You can handle the search functionality on the client side or redirect the user to a search results page with the query.
1// pages/404.js 2import React, { useState } from 'react'; 3import Link from 'next/link'; 4import Router from 'next/router'; 5 6export default function Custom404() { 7 const [searchTerm, setSearchTerm] = useState(''); 8 9 const handleSearch = (e) => { 10 e.preventDefault(); 11 Router.push(`/search?q=${searchTerm}`); 12 }; 13 14 return ( 15 <div> 16 <h1>404 - Page Not Found</h1> 17 <p>Can't find what you're looking for? Try searching:</p> 18 <form onSubmit={handleSearch}> 19 <input 20 type="text" 21 placeholder="Search..." 22 value={searchTerm} 23 onChange={(e) => setSearchTerm(e.target.value)} 24 /> 25 <button type="submit">Search</button> 26 </form> 27 <Link href="/"> 28 Or go back home 29 </Link> 30 </div> 31 ); 32}
Providing a list of suggested pages can help guide users back to relevant content on your site. This could be a list of popular pages, recent blog posts, or other resources that might interest the user. By offering alternatives, you're helping users to continue their journey on your website without much hassle.
1// Example of adding suggested pages to your custom 404 page 2// pages/404.js 3import React from 'react'; 4import Link from 'next/link'; 5 6export default function Custom404() { 7 const suggestedPages = [ 8 { href: '/about', title: 'About Us' }, 9 { href: '/contact', title: 'Contact Us' }, 10 { href: '/blog', title: 'Blog' }, 11 // ... other suggested pages 12 ]; 13 14 return ( 15 <div> 16 <h1>404 - Page Not Found</h1> 17 <p>Here are some pages you might find interesting:</p> 18 <ul> 19 {suggestedPages.map((page) => ( 20 <li key={page.href}> 21 <Link href={page.href}> 22 {page.title} 23 </Link> 24 </li> 25 ))} 26 </ul> 27 <Link href="/"> 28 Go back home 29 </Link> 30 </div> 31 ); 32}
While the 404 page is typically static and doesn't need to fetch data on each request, if you have dynamic content that you want to include, such as a list of popular pages or posts, you can use getStaticProps to fetch this data at build time.
However, it's worth noting that for the 404 page, Next.js does not allow getStaticProps or getServerSideProps as the page is static and should be instantly available to users.
Creating a custom 404 page is not just about aesthetics; it's also about maintaining good SEO practices, ensuring accessibility, and keeping track of how often users encounter these errors. Let's explore some best practices to make your 404 pages more effective and user-friendly.
Ensure that your server is returning a 404 HTTP status code when the custom 404 page is displayed. This tells search engines that the page does not exist, which is important for maintaining the integrity of your site's indexing.
Include links to your homepage, popular products, or content. This can help reduce bounce rates by giving users a clear path to continue browsing your site.
Make sure that your 404 page is not indexed by search engines. You can do this by including a noindex tag in the header of your 404 page to prevent it from appearing in search results.
Avoid using technical terms like "404 error" in your page title or headings. Instead, use language that is understandable to all users, such as "Page Not Found."
Semantic HTML elements like headings, paragraphs, and lists help screen readers understand the structure of your content. Use them appropriately on your 404 page to aid users who rely on assistive technologies.
If you use images or icons on your 404 page, make sure to include alt text that describes the image content. This ensures that users who cannot see the images can still understand the message being conveyed.
Make sure the text on your 404 page stands out against the background. This makes the content more accessible to those with visual impairments.
When a user lands on a 404 page, it can be helpful to direct their focus to the main message or a search box if available. This can be managed programmatically using JavaScript to improve the user experience for keyboard and screen reader users.
Set up your analytics tool to track 404 errors. This can help you understand how often users encounter these pages and identify any patterns or common missing URLs.
Regularly check your server logs for 404 errors. This can help you find broken links or incorrect URLs that users are trying to access.
If certain 404 errors are occurring frequently, it may indicate a problem that needs to be resolved. Set up alerts to notify you when these errors spike so you can address the underlying issues.
With these practices, you can ensure that your 404 pages are not only user-friendly but also optimized for search engines and accessible to all users. This can help maintain a positive user experience even when things don't go as planned, and it can provide valuable insights into areas of your site that may need attention.
In the digital landscape, encountering a 404 page is an inevitable part of the browsing experience. However, as we've explored in this blog, a custom 404 page in Next.js is not just a necessity—it's an opportunity. By creating a custom 404 page, you can turn potential frustration into a positive interaction, guiding users back to your content and reinforcing your brand's image.
A well-crafted 404 page should communicate clearly, maintain the look and feel of your site, and offer helpful navigation options. It's also important to adhere to SEO best practices, ensure accessibility for all users, and monitor occurrences of these errors to improve your site continuously.
We hope that the insights and tips shared here will inspire you to create a custom 404 page that reflects the thoughtfulness and care you put into every other aspect of your Next.js application.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.