Skip to content

ever-co/ever-works / .agents/skills/next-best-practices

next-best-practices

Verified

Next.js best practices - file conventions, RSC boundaries, data patterns, async APIs, metadata, error handling, route handlers, image/font optimization, bundling

FileKindSize
SKILL.mdskill md3.9 KB
async-patterns.mdmarkdown1.6 KB
bundling.mdmarkdown4.6 KB
data-patterns.mdmarkdown6.6 KB
debug-tricks.mdmarkdown2.9 KB
directives.mdmarkdown1.4 KB
error-handling.mdmarkdown4.6 KB
file-conventions.mdmarkdown3.7 KB
font.mdmarkdown5.0 KB
functions.mdmarkdown5.8 KB
hydration-error.mdmarkdown1.7 KB
image.mdmarkdown3.8 KB
metadata.mdmarkdown7.1 KB
parallel-routes.mdmarkdown7.1 KB
route-handlers.mdmarkdown3.3 KB
rsc-boundaries.mdmarkdown4.6 KB
runtime-selection.mdmarkdown986 B
scripts.mdmarkdown3.6 KB
self-hosting.mdmarkdown8.5 KB
suspense-boundaries.mdmarkdown1.4 KB

error-handling.md

View on GitHub
# Error Handling

Handle errors gracefully in Next.js applications.

Reference: https://nextjs.org/docs/app/getting-started/error-handling

## Error Boundaries

### `error.tsx`

Catches errors in a route segment and its children:

```tsx
'use client';

export default function Error({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
	return (
		<div>
			<h2>Something went wrong!</h2>
			<button onClick={() => reset()}>Try again</button>
		</div>
	);
}
```

**Important:** `error.tsx` must be a Client Component.

### `global-error.tsx`

Catches errors in root layout:

```tsx
'use client';

export default function GlobalError({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) {
	return (
		<html>
			<body>
				<h2>Something went wrong!</h2>
				<button onClick={() => reset()}>Try again</button>
			</body>
		</html>
	);
}
```

**Important:** Must include `<html>` and `<body>` tags.

## Server Actions: Navigation API Gotcha

**Do NOT wrap navigation APIs in try-catch.** They throw special errors that Next.js handles internally.

Reference: https://nextjs.org/docs/app/api-reference/functions/redirect#behavior

```tsx
'use server'

import { redirect } from 'next/navigation'
import { notFound } from 'next/navigation'

// Bad: try-catch catches the navigation "error"
async function createPost(formData: FormData) {
  try {
    const post = await db.post.create({ ... })
    redirect(`/posts/${post.id}`)  // This throws!
  } catch (error) {
    // redirect() throw is caught here - navigation fails!
    return { error: 'Failed to create post' }
  }
}

// Good: Call navigation APIs outside try-catch
async function createPost(formData: FormData) {
  let post
  try {
    post = await db.post.create({ ... })
  } catch (error) {
    return { error: 'Failed to create post' }
  }
  redirect(`/posts/${post.id}`)  // Outside try-catch
}

// Good: Re-throw navigation errors
async function createPost(formData: FormData) {
  try {
    const post = await db.post.create({ ... })
    redirect(`/posts/${post.id}`)
  } catch (error) {
    if (error instanceof Error && error.message === 'NEXT_REDIRECT') {
      throw error  // Re-throw navigation errors
    }
    return { error: 'Failed to create post' }
  }
}
```

Same applies to:

- `redirect()` - 307 temporary redirect
- `permanentRedirect()` - 308 permanent redirect
- `notFound()` - 404 not found
- `forbidden()` - 403 forbidden
- `unauthorized()` - 401 unauthorized

Use `unstable_rethrow()` to re-throw these errors in catch blocks:

```tsx
import { unstable_rethrow } from 'next/navigation';

async function action() {
	try {
		// ...
		redirect('/success');
	} catch (error) {
		unstable_rethrow(error); // Re-throws Next.js internal errors
		return { error: 'Something went wrong' };
	}
}
```

## Redirects

```tsx
import { redirect, permanentRedirect } from 'next/navigation';

// 307 Temporary - use for most cases
redirect('/new-path');

// 308 Permanent - use for URL migrations (cached by browsers)
permanentRedirect('/new-url');
```

## Auth Errors

Trigger auth-related error pages:

```tsx
import { forbidden, unauthorized } from 'next/navigation';

async function Page() {
	const session = await getSession();

	if (!session) {
		unauthorized(); // Renders unauthorized.tsx (401)
	}

	if (!session.hasAccess) {
		forbidden(); // Renders forbidden.tsx (403)
	}

	return <Dashboard />;
}
```

Create corresponding error pages:

```tsx
// app/forbidden.tsx
export default function Forbidden() {
	return <div>You don't have access to this resource</div>;
}

// app/unauthorized.tsx
export default function Unauthorized() {
	return <div>Please log in to continue</div>;
}
```

## Not Found

### `not-found.tsx`

Custom 404 page for a route segment:

```tsx
export default function NotFound() {
	return (
		<div>
			<h2>Not Found</h2>
			<p>Could not find the requested resource</p>
		</div>
	);
}
```

### Triggering Not Found

```tsx
import { notFound } from 'next/navigation';

export default async function Page({ params }: { params: Promise<{ id: string }> }) {
	const { id } = await params;
	const post = await getPost(id);

	if (!post) {
		notFound(); // Renders closest not-found.tsx
	}

	return <div>{post.title}</div>;
}
```

## Error Hierarchy

Errors bubble up to the nearest error boundary:

```
app/
├── error.tsx           # Catches errors from all children
├── blog/
│   ├── error.tsx       # Catches errors in /blog/*
│   └── [slug]/
│       ├── error.tsx   # Catches errors in /blog/[slug]
│       └── page.tsx
└── layout.tsx          # Errors here go to global-error.tsx
```
receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementationStars: 322kUpdated Claude CodeCodexVerifiedInstall
requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirementsStars: 322kUpdated Claude CodeCodexVerifiedInstall
using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallbackStars: 322kUpdated Claude CodeCodexVerifiedInstall
verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions alwaysStars: 322kUpdated Claude CodeCodexVerifiedInstall