Open In App

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
Article Tags :

Similar Reads