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

route-handlers.md

View on GitHub
# Route Handlers

Create API endpoints with `route.ts` files.

## Basic Usage

```tsx
// app/api/users/route.ts
export async function GET() {
	const users = await getUsers();
	return Response.json(users);
}

export async function POST(request: Request) {
	const body = await request.json();
	const user = await createUser(body);
	return Response.json(user, { status: 201 });
}
```

## Supported Methods

`GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`

## GET Handler Conflicts with page.tsx

**A `route.ts` and `page.tsx` cannot coexist in the same folder.**

```
app/
├── api/
│   └── users/
│       └── route.ts    # /api/users
└── users/
    ├── page.tsx        # /users (page)
    └── route.ts        # Warning: Conflicts with page.tsx!
```

If you need both a page and an API at the same path, use different paths:

```
app/
├── users/
│   └── page.tsx        # /users (page)
└── api/
    └── users/
        └── route.ts    # /api/users (API)
```

## Environment Behavior

Route handlers run in a **Server Component-like environment**:

- Yes: Can use `async/await`
- Yes: Can access `cookies()`, `headers()`
- Yes: Can use Node.js APIs
- No: Cannot use React hooks
- No: Cannot use React DOM APIs
- No: Cannot use browser APIs

```tsx
// Bad: This won't work - no React DOM in route handlers
import { renderToString } from 'react-dom/server';

export async function GET() {
	const html = renderToString(<Component />); // Error!
	return new Response(html);
}
```

## Dynamic Route Handlers

```tsx
// app/api/users/[id]/route.ts
export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
	const { id } = await params;
	const user = await getUser(id);

	if (!user) {
		return Response.json({ error: 'Not found' }, { status: 404 });
	}

	return Response.json(user);
}
```

## Request Helpers

```tsx
export async function GET(request: Request) {
	// URL and search params
	const { searchParams } = new URL(request.url);
	const query = searchParams.get('q');

	// Headers
	const authHeader = request.headers.get('authorization');

	// Cookies (Next.js helper)
	const cookieStore = await cookies();
	const token = cookieStore.get('token');

	return Response.json({ query, token });
}
```

## Response Helpers

```tsx
// JSON response
return Response.json({ data });

// With status
return Response.json({ error: 'Not found' }, { status: 404 });

// With headers
return Response.json(data, {
	headers: {
		'Cache-Control': 'max-age=3600'
	}
});

// Redirect
return Response.redirect(new URL('/login', request.url));

// Stream
return new Response(stream, {
	headers: { 'Content-Type': 'text/event-stream' }
});
```

## When to Use Route Handlers vs Server Actions

| Use Case                 | Route Handlers | Server Actions |
| ------------------------ | -------------- | -------------- |
| Form submissions         | No             | Yes            |
| Data mutations from UI   | No             | Yes            |
| Third-party webhooks     | Yes            | No             |
| External API consumption | Yes            | No             |
| Public REST API          | Yes            | No             |
| File uploads             | Both work      | Both work      |

**Prefer Server Actions** for mutations triggered from your UI.
**Use Route Handlers** for external integrations and public APIs.
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