How To Create A Custom 404 Page In Next Js App Router

Introduction

Redirecting to a page that is not found on your website is annoying and what makes it more annoying is the fact that the generic 404 page from next.js is ugly and you just hate yourself for going to a file that is not found. But there is nothing you can do except you make it pretty and that’s what we’re going to do in this article.

Understanding Next.js Routing in app router

Next.js has two options for routing but in this article, we’re only going to be working with the app router which is the recommended option for next.js. Routing in the app router is different from page router but we won’t be looking at that today.

Routing in the app router is pretty cool, you can define a unique route by creating a folder and putting “page.tsx” in it and it automatically handles client-side navigation.

Next.js has file conventions which are the rules or guidelines for naming files that define routes of your web application and will be looking at one of the files next.js has which is not-found.js which renders as the 404 page.

No offense but I honestly don’t want to see this UI when I redirect to a URL that is not found on your website.

Why a custom 404 page?

By customizing your 404 page you have the opportunity to turn a potential frustration for users into a unique and engaging experience. A customized 404 page will give the user a good experience because you have a detailed message telling them that they are on the wrong page and a button for them to redirect them to the homepage. You can make the page engaging by adding your brand identity like color, logo, image, etc., and something cool like what we’ll be doing today.

Setting Up a Next.js Project and Integrating Tailwind CSS

Let’s install the next.js project using this command

Take note of what I selected and do that for yours.

Creating the 404 Page and Adding Styles with Tailwind

Create a page called “not-found”

This page automatically becomes your custom 404 page.

Let’s write something inside and check out how it looks on the browser.

Woah, it works. So let’s make it pretty.

Use this code to update the style.

"use client";
import { useState, useEffect } from "react";
import Link from "next/link";

export default function NotFound() {
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });

  useEffect(() => {
    const handleMouseMove = (e: any) => {
      setMousePosition({ x: e.clientX, y: e.clientY });
    };

    if (typeof window !== "undefined") {
      window.addEventListener("mousemove", handleMouseMove);

      return () => {
        window.removeEventListener("mousemove", handleMouseMove);
      };
    }
  }, []);

  // Calculate the position of the white circle within the parent circle
  const parentCircleRadius = 50; // Adjust this based on your design

  // Check if window is defined before accessing mousePosition
  const deltaX =
    typeof window !== "undefined" ? mousePosition.x - window.innerWidth / 2 : 0;
  const deltaY =
    typeof window !== "undefined"
      ? mousePosition.y - window.innerHeight / 2
      : 0;

  const angle = Math.atan2(deltaY, deltaX);
  const whiteCircleX =
    typeof window !== "undefined" ? Math.cos(angle) * parentCircleRadius : 0;
  const whiteCircleY =
    typeof window !== "undefined" ? Math.sin(angle) * parentCircleRadius : 0;
  return (
    <div className="items-center flex justify-center flex-col h-full gap-5">
      <div className="flex items-center text-[#e85444] gap-5">
        <span className="text-[200px]">4</span>
        <span className="flex items-center justify-center relative">
          <span
            className="bg-[#e85444] rounded-full p-20"
            style={{
              top: `calc(50% - 10px)`,
              left: `calc(50% - 10px)`,
            }}
          >
            <span
              className="bg-[black] rounded-full p-3 absolute"
              style={{
                top: `calc(50% - 15px + ${whiteCircleY}px)`,
                left: `calc(50% - 15px + ${whiteCircleX}px)`,
              }}
            >
              <span className="rounded-full p-1 absolute"></span>
            </span>
          </span>
        </span>
        <span className="text-[200px]">4</span>
      </div>
      <h2 className="dark:text-white text-black font-semibold text-3xl">
        This Page does not exist
      </h2>
      <Link
        href="/"
        className="dark:text-white dark:hover:text-slate-300 underline transition-colors duration-300"
      >
        Return Home
      </Link>
    </div>
  );
}

Here is the preview.

Conclusion

I hope this article has successfully guided you on how to create your custom 404 page. Make sure to create a prettier UI for your 404 page.

24
Subscribe to my newsletter

Read articles from Precious Egwuenu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Precious Egwuenu
Precious Egwuenu

I am a web developer and a content creator. I enjoy sharing my knowledge to people.