Explore snippets
Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.
TypeScript Discriminated Union Reducer
Model reducer actions safely with exhaustive TypeScript checking.
type State = {
count: number;
label: string;
};
type Action =
| {
type: 'increment';
amount: number;
}
| {
type: 'rename';
label: string;
}
| {
type: 'reset';
};
export function reducer(
state: State,
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">
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 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> {
Reusable useDebouncedValue Hook
Delay a rapidly changing value before triggering searches, validation, or API requests.
'use client';
import { useEffect, useState } from 'react';
export function useDebouncedValue<T>(
value: T,
delay = 300,
): T {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
React Form Validation with useActionState
Manage form validation, submission status, and server-style action results with React useActionState.
'use client';
import { useActionState } from 'react';
type FormState = {
message: string;
errors: {
email?: string;
};
};
const initialState: FormState = {
message: '',
errors: {},
};
async function subscribe(
previousState: FormState,
PHP Read JSON Request Body
Read and validate a JSON request body in PHP.
<?php
$rawBody = file_get_contents('php://input');
$data = json_decode($rawBody, true);
if (!is_array($data) || json_last_error() !== JSON_ERROR_NONE) {
http_response_code(400);
echo json_encode(['error' => 'Invalid JSON body.']);
exit;
}
Bootstrap Modal Form Skeleton
A small Bootstrap 5 modal with a form and submit button.
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newItemModal">
New item
</button>
<div class="modal fade" id="newItemModal" tabindex="-1" aria-hidden="true">
<div class="modal-dialog">
Simple Form Validation
Validate a small form before submitting it.
const form = document.querySelector('#contactForm');
const emailInput = document.querySelector('#email');
const messageBox = document.querySelector('#formMessage');
form.addEventListener('submit', (event) => {
messageBox.textContent = '';
Basic Upload Validation
Validate upload error, size, and MIME type before accepting a file.
<?php
$file = $_FILES['avatar'] ?? null;
if (!$file || $file['error'] !== UPLOAD_ERR_OK) {
throw new RuntimeException('Upload failed.');
}
if ($file['size'] > 2 * 1024 * 1024) {
throw new RuntimeException('The file is too large.');
}
Safe Redirect Allow List
Redirect only to known internal paths instead of trusting user input.
<?php
$allowedRedirects = [
'/my-dashboard',
'/my-workspace',
'/my-billing',
];
$next = $_GET['next'] ?? '/my-dashboard';
if (!in_array($next, $allowedRedirects, true)) {
$next = '/my-dashboard';
}
header('Location: ' . $next);
exit;
Match Date YYYY-MM-DD
Match a simple ISO-style date format.
^\d{4}-\d{2}-\d{2}$
Validate Hex Color
Match CSS hex colors like #fff or #a1b2c3.
^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$
Match Email Address
A practical beginner regex for basic email-like text matching.
^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$