Bird
Raised Fist0
NextJSframework~5 mins

Error.tsx for route errors in NextJS

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction

An Error.tsx file helps show a friendly message when something goes wrong on a page. It stops the app from crashing and tells users there was a problem.

When a page fails to load due to a server or client error.
When you want to show a custom message instead of a blank or broken page.
When you want to catch unexpected errors in a route and handle them gracefully.
When you want to log errors or provide a way for users to retry or go back.
When you want consistent error pages across your Next.js app.
Syntax
NextJS
'use client';
import { useEffect } from 'react';

export default function Error({ error, reset }) {
  useEffect(() => {
    console.error(error);
  }, [error]);

  return (
    <main role="alert" aria-live="assertive" style={{ padding: '2rem', textAlign: 'center' }}>
      <h1>Oops! Something went wrong.</h1>
      <p>{error.message}</p>
      <button onClick={() => reset()}>Try again</button>
    </main>
  );
}

The Error component receives an error object and a reset function.

Use aria-live="assertive" and role="alert" for accessibility so screen readers announce the error.

Examples
A simple error component showing the error message and a reload button.
NextJS
'use client';

export default function Error({ error, reset }) {
  return (
    <div>
      <h2>Error occurred:</h2>
      <p>{error.message}</p>
      <button onClick={reset}>Reload</button>
    </div>
  );
}
A minimal error display with red text.
NextJS
export default function Error({ error }) {
  return <p style={{ color: 'red' }}>Error: {error.message}</p>;
}
Sample Program

This Error.tsx component catches route errors in Next.js. It logs the error to the console for developers and shows a clear message to users. The button calls reset() to retry loading the route.

NextJS
'use client';
import { useEffect } from 'react';

export default function Error({ error, reset }) {
  useEffect(() => {
    console.error('Route error:', error);
  }, [error]);

  return (
    <main role="alert" aria-live="assertive" style={{ padding: '2rem', textAlign: 'center', fontFamily: 'Arial, sans-serif' }}>
      <h1>Oops! Something went wrong.</h1>
      <p>{error.message}</p>
      <button onClick={() => reset()} style={{ padding: '0.5rem 1rem', fontSize: '1rem', cursor: 'pointer' }}>
        Try again
      </button>
    </main>
  );
}
OutputSuccess
Important Notes

Always include aria-live and role attributes for screen reader users.

The reset function helps users retry loading the page without refreshing the whole browser.

Logging errors in useEffect helps developers find issues during debugging.

Summary

Error.tsx shows friendly messages when routes fail.

It improves user experience by preventing blank or broken pages.

Use accessibility features and provide a retry button for best results.

Practice

(1/5)
1. What is the main purpose of the Error.tsx file in a Next.js route?
easy
A. To define the main layout of the application
B. To display a friendly message when a route fails or an error occurs
C. To handle user authentication and login
D. To fetch data from an API for the route

Solution

  1. Step 1: Understand the role of Error.tsx in Next.js

    Error.tsx is designed to catch errors in routes and show a user-friendly message instead of a broken page.
  2. Step 2: Compare with other options

    Layouts, authentication, and data fetching are handled elsewhere, not in Error.tsx.
  3. Final Answer:

    To display a friendly message when a route fails or an error occurs -> Option B
  4. Quick Check:

    Error.tsx shows friendly error messages [OK]
Hint: Error.tsx shows errors, not layouts or data [OK]
Common Mistakes:
  • Confusing Error.tsx with layout or data files
  • Thinking Error.tsx handles authentication
  • Assuming Error.tsx fetches API data
2. Which of the following is the correct way to export a default Error component in Error.tsx for Next.js?
easy
A. export function Error() { return
Error occurred
; }
B. function Error() { return
Error occurred
; }
C. export default function Error() { return
Error occurred
; }
D. default export function Error() { return
Error occurred
; }

Solution

  1. Step 1: Recall correct default export syntax in React/Next.js

    The correct syntax is to declare the function and export it as default in one statement.
  2. Step 2: Identify syntax errors in other options

    function Error() { return
    Error occurred; } misses export, C exports a named function, D has invalid syntax.
  3. Final Answer:

    export default function Error() { return <div>Error occurred</div>; } -> Option C
  4. Quick Check:

    Default export uses 'export default function' [OK]
Hint: Default export needs 'export default function' [OK]
Common Mistakes:
  • Forgetting to export the component
  • Using named export instead of default
  • Incorrect export syntax like 'default export'
3. Given this Error.tsx component, what will be rendered when an error occurs?
export default function Error() {
  return (
    <main role="alert" aria-live="assertive">
      <h1>Oops! Something went wrong.</h1>
      <button onClick={() => window.location.reload()}>Try Again</button>
    </main>
  );
}
medium
A. A heading with an error message and a button to reload the page
B. A blank page with no content
C. Only a button that does nothing
D. An error stack trace displayed to the user

Solution

  1. Step 1: Analyze the JSX returned by the Error component

    The component returns a main element with a heading and a button that reloads the page on click.
  2. Step 2: Understand the button behavior

    The button triggers window.location.reload(), so it reloads the current page when clicked.
  3. Final Answer:

    A heading with an error message and a button to reload the page -> Option A
  4. Quick Check:

    Error component shows message + reload button [OK]
Hint: Look for JSX elements and button onClick behavior [OK]
Common Mistakes:
  • Assuming no content renders
  • Thinking button does nothing
  • Expecting error stack trace to show
4. What is wrong with this Error.tsx component code?
export default function Error() {
  return (
    <div>
      <h1>Error!</h1>
      <button onClick={reloadPage}>Reload</button>
    </div>
  );
}

function reloadPage() {
  location.reload;
}
medium
A. The reloadPage function does not call location.reload() correctly
B. The button should not have an onClick handler
C. The component must use a <main> tag instead of <div>
D. The function reloadPage should be inside the component

Solution

  1. Step 1: Check the reloadPage function implementation

    location.reload is a function and must be called with parentheses: location.reload()
  2. Step 2: Verify other parts

    The button can have onClick, using div is allowed, and reloadPage can be outside the component.
  3. Final Answer:

    The reloadPage function does not call location.reload() correctly -> Option A
  4. Quick Check:

    Call functions with parentheses to execute [OK]
Hint: Check if functions are called with () [OK]
Common Mistakes:
  • Forgetting parentheses on function calls
  • Thinking onClick is invalid on button
  • Believing HTML tags must be <main>
5. You want to improve accessibility in your Error.tsx component by adding ARIA roles and live regions. Which of these changes is best practice?
hard
A. Use a <div> with aria-hidden="true" around the error message
B. Remove all ARIA attributes to keep it simple
C. Add tabindex="-1" to the button only
D. Wrap the error message in a <main> with role="alert" and aria-live="assertive"

Solution

  1. Step 1: Understand ARIA roles for error messages

    Using role="alert" and aria-live="assertive" notifies screen readers immediately about errors.
  2. Step 2: Evaluate other options

    aria-hidden="true" hides content from screen readers, tabindex="-1" on button is unrelated, removing ARIA reduces accessibility.
  3. Final Answer:

    Wrap the error message in a <main> with role="alert" and aria-live="assertive" -> Option D
  4. Quick Check:

    Use role="alert" and aria-live for error accessibility [OK]
Hint: Use role="alert" and aria-live="assertive" for errors [OK]
Common Mistakes:
  • Hiding error messages from screen readers
  • Misusing tabindex on unrelated elements
  • Removing ARIA attributes thinking they are optional