Next.js Functions: notFound
Last Updated :
22 Jul, 2024
Next.js is a React framework that is used to build full-stack web applications. It is used both for front-end and back-end development, simplifying React development with powerful features. In this article, we will explore the notFound function, which is used to handle cases where a requested resource cannot be found, allowing developers to gracefully manage 404 errors and enhance the user experience.
notFound Function
The notFound function in Next.js is used to indicate that a requested resource does not exist, triggering a 404 error page. It is particularly useful in scenarios where you need to dynamically handle missing data or pages. The function is imported from next/navigation and can be called to render a 404 error page when a condition is met.
Syntax
import { notFound } from 'next/navigation';
// Call the function when a resource is not found
notFound();
Steps to Create NextJS Application:
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
Folder Structure
Next.js folder structureDependencies
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.5"
},
Example: The below example demonstrates the use of notFound function.
In this example, we are using the notFound function from Next.js to handle cases where a resource is not found. The page allows users to input an ID, and if the ID is '123', it displays valid data. For any other input, it triggers the notFound function, which simulates a 404 error, showing an error message. The component is marked as a Client Component with 'use client' to use client-side features like useState.
JavaScript
// src/app/page.js
'use client';
import { useState } from 'react';
import { notFound } from 'next/navigation';
export default function Page() {
const [input, setInput] = useState('');
const [data, setData] = useState(null);
const [error, setError] = useState('');
const fetchData = async () => {
if (input === '123') {
setData({ id: '123', name: 'Valid Resource' });
setError('');
} else {
setData(null);
setError('Resource not found');
notFound(); // Handle 404
}
};
return (
<div style={{ textAlign: 'center', padding: '20px' }}>
<h1 style={{ color: 'green' }}>GeeksforGeeks</h1>
<h3>NextJS: notFound Function Example</h3>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Enter resource ID"
style={{ padding: '10px', margin: '10px' }}
/>
<button onClick={fetchData} style={{ padding: '10px', margin: '10px' }}>
Fetch Data
</button>
{error && <p style={{ color: 'red' }}>{error}</p>}
{data && <p>Data: {JSON.stringify(data)}</p>}
</div>
);
}
To run the Application open the terminal in the project folder and enter the following command:
npm run dev
Output
Next.js Functions: notFoundUsage
- Using
notFound
in getServerSideProps
: getServerSideProps
is used for server-side rendering (SSR) and runs on each request. If a page or resource is not found, you can use notFound
to trigger a 404 page. - Using
notFound
in getStaticProps
: getStaticProps
is used for static site generation (SSG) and runs at build time. You can use notFound
if the data required for the page is not available.
Similar Reads
Underscore.js _.negate() Function
Underscore.js is a JavaScript library that provides a lot of useful functions that help in the programming in a big way like the map, filter, invoke, etc even without using any built-in objects. The _.negate() function is an inbuilt function in Underscore.js library of JavaScript which is used to fi
1 min read
Underscore.js _.noop() Function
Underscore.js is a JavaScript library that makes operations on arrays, string, objects much easier and handy. The _.noop() function is used to return "undefined" irrespective of the arguments passed to it. Note: It is very necessary to link the underscore CDN before going and using underscore functi
2 min read
JavaScript Nested functions
A nested function (also known as an inner function) is a function that is declared within another function (known as the outer function). The inner function has access to the variables of its outer function, forming a lexical scope chain. [GFGTABS] JavaScript function outer() { console.log('This
5 min read
Underscore.js _.without() Function
Underscore.js _.without() function is used to return a copy of the array which contains all the array except values. Syntax:_.without( array, *values );Parameters:array: This parameter is used to hold the list of array elements.values: This parameter is used to hold the value that needs to be remove
3 min read
Underscore.js _.noConflict() Function
Underscore.js is a library in javascript that makes operations on arrays, string, objects much easier and handy. The _.noConflict() function is used to create a reference of the global underscore object "_" to another variable. Note: It is very necessary to link the underscore CDN before going and u
2 min read
p5.js | value() Function
The value() function is an inbuilt function which is used to set or return the value of the element.This function requires p5.dom library. So add the following line in the head section of the index.html file. C/C++ Code <script language="javascript" type="text/javascript" src=
2 min read
JQuery | isFunction() method
This isFunction() Method in jQuery is used to determines if its argument is callable as a function. Syntax: jQuery.isFunction( value ) Parameters: The isFunction() method accepts only one parameter that is mentioned above and described below: value : This parameter is the value to be tested. Return
2 min read
Lodash _.isFunction() Method
Lodash _.isFunction() Method checks whether the given value is a function object or not and returns the corresponding boolean value. Syntax:_.isFunction( value )Parameters:This method accepts a single parameter as mentioned above and described below: value: This parameter holds the value that to be
2 min read
Less.js Type isurl() Function
Less.js is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is better since CSS uses a dynamic style sheet language. LESS is flexible enough to be utilized by a wide range of browsers. Web browsers can only use CSS if it
3 min read
Lodash _.isNumber() Function
Lodash _.isNumber() method is used to find whether the given value parameter is a number or not. If the given value is a number then it returns True value otherwise, it returns False. Syntax:_.isNumber(value); Parameters:value: This parameter holds the value to check.Return Value: This method return
2 min read