Next.js 14 provides an easy way to create custom 404 Not Found pages for your web application. In this blog post, we'll create and customize a 404 page to enhance your user experience.
Why Create a Custom 404 Page?
A custom 404 page allows you to:
- Maintain your site's branding and design
- Provide helpful information to users who've reached a non-existent page
- Offer navigation options to guide users back to valid content
Steps to Create a Custom 404 Page
1. Create the 404 File
In Next.js 14, creating a custom 404 page is as simple as adding a not-found.js
or not-found.tsx
file to your app directory.
app/
├── not-found.js (or not-found.tsx)
└── layout.js
2. Design Your 404 Page
Let's create a basic 404 page. Here's an example of what your not-found.js might look like:
import Link from 'next/link'
export default function NotFound() {
return (
<div className="flex flex-col items-center justify-center min-h-screen bg-gray-100">
<h1 className="text-6xl font-bold text-gray-800 mb-4">404</h1>
<h2 className="text-2xl font-semibold text-gray-600 mb-4">Page Not Found</h2>
<p className="text-gray-500 mb-8">Oops! The page you're looking for doesn't exist.</p>
<Link href="/" className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 transition-colors">
Go back home
</Link>
</div>
)
}
This example uses Tailwind CSS for styling. If you're not using Tailwind, you can replace the className
attributes with your own CSS.
3. Customize Your 404 Page
Feel free to customize the content and styling of your 404 page. You might want to add:
- Your company logo
- A search bar to help users find what they're looking for
- Links to popular pages on your site
- A contact form or link to report broken links
- Games to interact with users
4. Testing Your 404 Page
To test your custom 404 page:
- Run your Next.js development server
- Navigate to a non-existent route (e.g.,
http://localhost:3000/this-page-does-not-exist
) - You should see your custom 404 page instead of the default Next.js 404 page.
Conclusion
And there you have it! With just a few lines of code, you've transformed the dreaded 404 error into an opportunity to delight your users.
Happy coding, and may your users never be truly lost again! 🚀✨
P.S. If you come up with any cool 404 page ideas, drop them in the comments. I'm always looking for inspiration!
Top comments (0)