Error Handling

📘 Next.js 👁 29 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Error handling is essential to create robust and user-friendly applications. Next.js provides several ways to handle errors in pages, API routes, and layouts.


1. Error Handling in Pages

Using try-catch for async operations

export default async function Page() { try { const res = await fetch('https://api.example.com/posts'); if (!res.ok) throw new Error('Failed to fetch posts'); const data = await res.json(); return <div>{data.length} posts loaded</div>; } catch (error) { return <div>Error: {error.message}</div>; } }

2. Error Boundaries

React 18 supports error boundaries to catch runtime errors in components.

'use client'; import { Component } from 'react'; export class ErrorBoundary extends Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError() { return { hasError: true }; } render() { if (this.state.hasError) return <h2>Something went wrong.</h2>; return this.props.children; } }

Usage:

<ErrorBoundary> <MyComponent /> </ErrorBoundary>

3. error.js in App Router

In App Router, you can create error.js inside a route folder to handle route-specific errors.

app/ └── dashboard/ ├── page.js └── error.js
'use client'; export default function DashboardError({ error, reset }) { return ( <div> <h2>Something went wrong:</h2> <p>{error.message}</p> <button onClick={() => reset()}>Try Again</button> </div> ); }
  • error contains the thrown error

  • reset reloads the page or route


4. Catch-All Errors in API Routes

export async function GET() { try { const res = await fetch('https://api.example.com/posts'); if (!res.ok) throw new Error('Failed to fetch posts'); const data = await res.json(); return new Response(JSON.stringify(data), { status: 200 }); } catch (error) { return new Response(JSON.stringify({ error: error.message }), { status: 500, }); } }

5. 404 Not Found Pages

Next.js supports custom 404 pages using not-found.js.

app/ └── not-found.js
export default function NotFound() { return <h1>Page Not Found</h1>; }

6. Error Logging

  • Use console logs for development

  • Integrate monitoring tools like Sentry or LogRocket for production

  • Log errors in API routes for debugging


7. Best Practices

  • Handle both server-side and client-side errors

  • Provide user-friendly error messages

  • Catch API errors in both page and client components

  • Use error.js for route-level error handling in App Router

  • Integrate logging for monitoring


Conclusion

Next.js provides a flexible error handling system using try-catch, error boundaries, API error handling, and route-specific error pages. Proper error handling improves user experience, debugging, and application stability.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes