Next JS File Conventions: error.js
Last Updated :
20 Aug, 2024
Next.js manages file conventions to perform error handling within your application. By using error.js, you can define how your application responds to errors at the page or application level. This file allows you to create custom error pages that handle exceptions gracefully and provide users with a consistent experience even when things go wrong.
Error.js File
In Next.js, the error.js file is used to handle errors that occur within a specific route. It allows you to define a custom error page for that route, providing a way to display error messages or fallback content. This file is useful for managing error states and improving user experience when something goes wrong on a particular page.
Syntax:
// error.js
import React from 'react';
function Error({ error, reset }) {
return (
<div>
<h1>Something went wrong!</h1>
<p>{error.message}</p>
<button onClick={() => reset()}>Try Again</button>
</div>
);
}
export default Error;
Props:
Error
- error.message: This contains the error message that describes what went wrong. For example, if there was a network issue, error.message might be "Failed to fetch data".
- error.digest: This is an optional property that might contain additional information or an identifier related to the error. It is used internally by Next.js to group errors.
Reset
- This function is provided to allow you to reset the error boundary. When called, it attempts to re-render the component tree from scratch, potentially resolving the error. This can be useful if you want to allow users to try the operation again or if the error was transient.
global-error.js
The global-error.js file is used to handle errors at the root level of your application. It provides a global Error Boundary, making sure that any uncaught errors anywhere in the app are handled gracefully.
Example: This file is crucial for handling errors that affect the entire application. Since it replaces the root layout, you need to manually define the <html> and <body> structure within this file. You can use React Developer Tools to manually toggle error boundaries while designing the error UI.
JavaScript
'use client';
export default function GlobalError({ error, reset }) {
return (
<html>
<body>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</body>
</html>
);
}
not-found.js
The not-found.js file is used to handle cases where a specific route or resource cannot be found. This is particularly useful for displaying custom 404 pages.
Example: When the notFound() function is thrown within a route segment, Next.js renders the UI defined in not-found.js. It provides a clear and customizable way to display a "Not Found" message to users.
JavaScript
export default function NotFound() {
return (
<div>
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
</div>
);
}
Steps to Implement page File Convention in Next JS:
Step 1: Create a Next.js application using the following command.
npx create-next-app@latest gfg
Step 2: It will ask you some questions, so choose as the following.
√ Would you like to use TypeScript? ... No
√ Would you like to use ESLint? ... Yes
√ Would you like to use Tailwind CSS? ... No
√ Would you like to use `src/` directory? ... Yes
√ Would you like to use App Router? (recommended) ... Yes
√ Would you like to customize the default import alias (@/*)? ... Yes
Step 3: After creating your project folder i.e. gfg, move to it using the following command.
cd gfg
Step 4: Create error.js file in the directory src/app.
Folder Structure:
The updated dependencies in package.json file:
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.5"
},
Example: This demonstrates the implementation of error boundaries in Next.js with error.js to catch and handle errors, providing a fallback UI and recovery option.
JavaScript
// src/app/error.js
"use client";
import { useEffect } from 'react'
export default function Error({ error, reset }) {
useEffect(() => {
console.error('Error:', error)
}, [error])
return (
<div style={{ textAlign: 'center', padding: '20px' }}>
<h2>Something went wrong!</h2>
<p>{error.message || 'An unexpected error occurred.'}</p>
<button
onClick={() => {
reset()
}}
style={{ marginTop: '10px', padding: '10px 20px' }}
>
Try again
</button>
</div>
)
}
JavaScript
// src/app/page.js
"use client";
import { useState } from 'react'
export default function Page() {
const [throwError, setThrowError] = useState(false)
if (throwError) {
throw new Error('Simulated error in Dashboard Page.')
}
return (
<div style={{ textAlign: 'center', padding: '20px' }}>
<h1 style={{ color: 'green' }}>GeeksforGeeks</h1>
<h3>Next JS File Conventions: error.js</h3>
<button
onClick={() => setThrowError(true)}
style={{ padding: '10px 20px' }}
>
Trigger Error
</button>
</div>
)
}
To run the Application open the terminal in the project folder and enter the following command:
npm run dev
Output:
Summary
Using error.js in Next.js enables developers to create custom, user-friendly error pages, enhancing the overall user experience and providing clear, actionable feedback when issues arise.
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() {
6 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React Projects involve displaying data collections- like user profiles, product catalogs, or tasks- understanding how to work with lists.To render
4 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. the When rendering a list, you need to assign a unique key prop to each element i
4 min read
Components in React
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects