0
0
NextJSframework~5 mins

Not-found page handling in NextJS

Choose your learning style9 modes available
Introduction

Not-found page handling shows a friendly message when a user visits a page that does not exist. It helps users understand they reached a wrong address.

When a user types a wrong URL in the browser.
When a link points to a page that was removed.
When a user tries to access a page that requires special permissions but is not available.
When a dynamic page ID does not match any data.
When you want to improve user experience by guiding users back to valid pages.
Syntax
NextJS
export default function NotFound() {
  return (
    <main>
      <h1>404 - Page Not Found</h1>
      <p>Sorry, we couldn't find the page you are looking for.</p>
    </main>
  )
}
This component is placed in the special file named 'not-found.tsx' inside the app directory.
Next.js automatically shows this page when no matching route is found.
Examples
A simple not-found page with a short message.
NextJS
export default function NotFound() {
  return <h1>Oops! This page does not exist.</h1>
}
This example adds a link to help users return to the homepage.
NextJS
export default function NotFound() {
  return (
    <main>
      <h1>404 - Not Found</h1>
      <p>Try going back to the <a href="/">homepage</a>.</p>
    </main>
  )
}
Sample Program

This is a complete not-found page component with inline styles for spacing and color. It includes an accessible link back to the homepage.

NextJS
export default function NotFound() {
  return (
    <main style={{ padding: '2rem', textAlign: 'center' }}>
      <h1 style={{ fontSize: '2rem', color: '#c00' }}>404 - Page Not Found</h1>
      <p>Sorry, we couldn't find the page you are looking for.</p>
      <a href="/" style={{ color: '#06c', textDecoration: 'underline' }} aria-label="Go back to homepage">Go back home</a>
    </main>
  )
}
OutputSuccess
Important Notes

Place the not-found.tsx file inside the app folder for Next.js to use it automatically.

Use semantic HTML like <main> and <h1> for better accessibility.

Provide a clear message and a way to navigate back to valid pages to improve user experience.

Summary

Not-found pages show a message when a page does not exist.

In Next.js, create a not-found.tsx file inside the app directory.

Use simple, clear messages and links to help users find their way.