Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • jQuery
  • AngularJS
  • ReactJS
  • Next.js
  • React Native
  • NodeJS
  • Express.js
  • MongoDB
  • MERN Stack
  • PHP
  • WordPress
  • Bootstrap
  • Tailwind
  • CSS Frameworks
  • JS Frameworks
  • Web Development
Open In App
Next Article:
Next.js Functions: notFound
Next article icon

Next.js Functions: notFound

Last Updated : 22 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

PS
Next.js folder structure

Dependencies

"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

1(1)
Next.js Functions: notFound

Usage

  1. 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.
  2. 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.

Next Article
Next.js Functions: notFound

G

gauravggeeksforgeeks
Improve
Article Tags :
  • Web Technologies
  • Next.js

Similar Reads

    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 ch
    2 min read
    Underscore.js _.isNaN() Function
    _.isNaN() function:  It is used to find whether the value of the object passed is NaN or not.If the object's value is NaN then the output will be true otherwise, it will be false.We can even perform addition, subtraction etc operations in this function. Syntax:  _.isNaN(object) Parameters:It takes o
    3 min read
    JavaScript uneval() Function
    The uneval() is an inbuilt function in JavaScript that is used to create a string representation of the source code of an Object. Syntax: uneval(object) Note: This function has been DEPRECATED and is no longer recommended. Parameters: It accepts an object which may be a JavaScript expression or stat
    2 min read
    Underscore.js _.isNull() Function
    Underscore.js _.isNull() function It is used to find whether the value of the object is null. If an object has a null value then the output will be true otherwise false. We can even perform addition, subtraction, etc operations in this function. Syntax: _.isNull(object);Parameters:It takes only one
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences