Explore snippets
Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.
Parallel Data Fetching in a Server Component
Start independent server requests together to reduce total rendering time.
// app/dashboard/page.tsx
async function getUser() {
return db.user.findFirst();
}
async function getRecentOrders() {
return db.order.findMany({
orderBy: {
createdAt: 'desc',
},
take: 5,
});
}
Next.js Route Error Boundary
Handle uncaught route segment errors and let the user retry without a full reload.
// app/dashboard/error.tsx
'use client';
import { useEffect } from 'react';
type ErrorPageProps = {
error: Error & {
digest?: string;
};
reset: () => void;
};
export default function DashboardError({
error,
reset,
}: ErrorPageProps) {
Next.js Loading Skeleton
Provide instant loading UI for an App Router segment with loading.tsx.
// app/dashboard/loading.tsx
export default function DashboardLoading() {
return (
<main aria-busy="true" aria-label="Loading dashboard">
<div className="skeleton skeleton-title" />
<div className="skeleton-grid">
Dynamic Metadata with generateMetadata
Generate page-specific SEO metadata from a dynamic App Router route.
// app/blog/[slug]/page.tsx
import type { Metadata } from 'next';
type PageProps = {
params: Promise<{
slug: string;
}>;
};
async function getPost(slug: string) {
return db.post.findUnique({
where: { slug },
select: {
title: true,
Next.js Route Handler with JSON Validation
Validate a JSON request body and return typed responses from an App Router Route Handler.
// app/api/tasks/route.ts
import { NextResponse } from 'next/server';
type CreateTaskBody = {
title?: unknown;
};
export async function POST(request: Request) {
let body: CreateTaskBody;
try {
body = await request.json();
} catch {
Revalidate a Next.js Cache Tag after Mutation
Mark tagged data stale after a Server Action changes the underlying records.
// app/actions/posts.ts
'use server';
import { revalidateTag } from 'next/cache';
export async function publishPost(postId: string) {
const post = await db.post.update({
where: {
id: postId,
},
data: {
published: true,
},
});
Next.js Cached Data with use cache
Cache a server data function and attach a reusable invalidation tag.
// app/lib/posts.ts
import {
cacheLife,
cacheTag,
} from 'next/cache';
export async function getPublishedPosts() {
'use cache';
cacheLife('hours');
cacheTag('posts');
return db.post.findMany({
where: {
published: true,
},
Next.js Proxy Authentication Guard
Redirect unauthenticated requests from protected routes with the Next.js proxy convention.
// proxy.ts
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
export function proxy(request: NextRequest) {
const sessionId = request.cookies.get('session')?.value;
if (!sessionId) {
Next.js Server Action Form with useActionState
Connect a Next.js Server Action to a client form with validation and pending state.
// app/actions.ts
'use server';
export type CreateUserState = {
message: string;
errors: {
email?: string;
};
};
export async function createUser(
previousState: CreateUserState,
formData: FormData,
): Promise<CreateUserState> {
Dynamic Page with notFound
Render the nearest not-found UI when a requested App Router record does not exist.
// app/products/[id]/page.tsx
import { notFound } from 'next/navigation';
type PageProps = {
params: Promise<{
id: string;
}>;
};
export default async function ProductPage({
params,
}: PageProps) {
const { id } = await params;