Explore snippets
Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.
Cross-Tab State Sync with BroadcastChannel
Synchronize lightweight UI state between tabs from the same origin.
const channel = new BroadcastChannel('app-preferences');
const preferences = {
theme: 'dark',
compactMode: true,
};
channel.addEventListener('message', (event) => {
if (event.data?.type !== 'preferences-updated') {
return;
}
Promise-Based IndexedDB Key-Value Store
Store structured values in IndexedDB with a small promise-based wrapper.
const databaseName = 'app-cache';
const storeName = 'key-value';
function openDatabase(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(databaseName, 1);
Web Worker for CPU-Heavy Calculations
Move expensive calculations off the main thread and return the result with postMessage.
// statistics.worker.js
self.addEventListener('message', (event) => {
const numbers = event.data;
const total = numbers.reduce(
(sum, value) => sum + value,
0,
);
self.postMessage({
total,
average: numbers.length
Infinite Scroll with IntersectionObserver
Load the next page when a sentinel approaches the viewport and prevent duplicate requests.
const sentinel = document.querySelector('[data-load-more]');
let page = 1;
let isLoading = false;
let hasMore = true;
const observer = new IntersectionObserver(
async (entries) => {
const entry = entries[0];
Typed JSON Fetch Helper
Wrap fetch with JSON parsing, typed responses, and useful HTTP error messages.
type ApiErrorBody = {
message?: string;
};
export async function fetchJson<T>(
input: RequestInfo | URL,
init?: RequestInit,
): Promise<T> {
const response = await fetch(input, {
...init,
headers: {
Accept: 'application/json',
Async Generator for Paginated API Data
Iterate through paginated API responses without loading every page into memory.
type Page<T> = {
items: T[];
nextCursor: string | null;
};
export async function* paginate<T>(
buildUrl: (cursor: string | null) => string,
): AsyncGenerator<T, void, void> {
let cursor: string | null = null;
do {
Process Mixed Results with Promise.allSettled
Run independent asynchronous tasks and keep both successful and failed outcomes.
async function loadDashboardResources() {
const requests = [
fetch('/api/profile').then((response) => response.json()),
fetch('/api/projects').then((response) => response.json()),
fetch('/api/notifications').then((response) => response.json()),
URLSearchParams Filter State
Read, update, and remove page filters without manually concatenating query strings.
function updateFilters(changes) {
const url = new URL(window.location.href);
Object.entries(changes).forEach(([key, value]) => {
const normalizedValue = String(value ?? '').trim();
if (normalizedValue === '') {
url.searchParams.delete(key);
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 {
Online Status with useSyncExternalStore
Subscribe to the browser online state through React useSyncExternalStore.
'use client';
import { useSyncExternalStore } from 'react';
function subscribe(callback: () => void) {
window.addEventListener('online', callback);
window.addEventListener('offline', callback);
return () => {
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(() => {
cURL GET Request in PHP
Call an external API with cURL and decode the JSON response.
<?php
$ch = curl_init('https://api.example.com/items');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
]);
$responseBody = curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
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;
}
PHP JSON Response Helper
Return a JSON response from a small PHP endpoint.
<?php
function json_response(array $payload, int $status = 200): void
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
Fetch POST JSON Request
Send JSON data to a backend endpoint with fetch.
async function createNote(note) {
const response = await fetch('/api/notes', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(note)
});
if (!response.ok) {
Fetch GET Request
Load JSON from an API endpoint with async and await.
async function searchSnippets(query) {
const url = `/api/snippets?search=${encodeURIComponent(query)}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error('Search request failed.');
}
Fetch JSON with Error Handling
Fetch JSON data and handle HTTP errors cleanly.
async function loadProfile() {
const response = await fetch('/api/profile');
if (!response.ok) {
throw new Error(`Request failed: ${response.status}`);
}
return await response.json();
}
loadProfile()
Safe HTML Escape Helper
A small PHP helper for escaping output in HTML templates.
<?php
function e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
$title = '<script>alert("xss")</script>';
echo '<h1>' . e($title) . '</h1>';
Copy Text to Clipboard
A vanilla JavaScript helper to copy text to the clipboard with a fallback message.
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
console.log('Copied to clipboard');
return true;
} catch (error) {
console.error('Clipboard copy failed:', error);
return false;
}
}