Wednesday, November 20, 2024
Google search engine
HomeLanguagesHow to create a custom error page in Next.js ?

How to create a custom error page in Next.js ?

NextJS is a react based framework which gives a developer all the features needed for production. Next.js is a react based framework. It has powers to Develop beautiful Web application for different platform like Windows, Linux and mac. 

In this post we are going to create a custom error page or a custom 404 page in a Next JS website.

What is a custom error / 404 page?

The 404 page is shown when the requested resource or the requested URL cannot be found on the server and as a response, it returns a 404 page. By default Next Js provides a static 404 page as shown below:

Default 404 / error page

Creating a custom error / 404 page

To create a custom 404 page, you first need to create a “404.js” named file in your pages directory. This file is statically generated at build time.

creating a 404,js file

In this page create and export a custom component and the rest will be taken care of by Next Js.

Javascript




// Inside the "pages/404.js" file add the below code
 
export default function Custom404() {
    return <> YOUR COMPONENT HERE </>
}


 

 

Example: Creating a custom error page in Next.js. Write down the following code in 404.js file.

 

Javascript




// Inside the "pages/404.js" file
export default function Custom404() {
    return (
        <div>
            <h1>
                Welcome to <span style={{ color: "green" }}>
                    GeeksForGeeks
                </span>
            </h1>
             
<p>Sorry , The page you are looking for can't be found</p>
 
             
<p>Try checking your URL</p>
 
 
            <h2>
                This is a <span style={{ color: "red" }}>404 page</span>
            </h2>
        </div>
    );
}


 

 

Step to Run the application: Now to start the development server you have to type the below command in the terminal.

 

npm run dev 

Output: And now let us go to a non-existing page on the website to encounter the 404 error.

 

Custom 404 page (created using the above code)

 

Note: You can use getStaticProps inside this page if you need to fetch data at build time.

 

Reference: https://nextjs.org/docs/advanced-features/custom-error-page#404-page

 

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments