Explore

Explore snippets

Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.

Public snippets by CodShot user
Clear
19 public snippets
Open
JavaScript
Public

Cross-Tab State Sync with BroadcastChannel

Synchronize lightweight UI state between tabs from the same origin.

JavaScript Preview
const channel = new BroadcastChannel('app-preferences');

const preferences = {
  theme: 'dark',
  compactMode: true,
};

channel.addEventListener('message', (event) => {
  if (event.data?.type !== 'preferences-updated') {
    return;
  }
#javascript #broadcastchannel #browser-api #state
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #240
Open
TypeScript
Public

Promise-Based IndexedDB Key-Value Store

Store structured values in IndexedDB with a small promise-based wrapper.

TypeScript Preview
const databaseName = 'app-cache';
const storeName = 'key-value';

function openDatabase(): Promise<IDBDatabase> {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(databaseName, 1);
#typescript #indexeddb #browser-api #storage
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #239
Open
JavaScript
Public

Web Worker for CPU-Heavy Calculations

Move expensive calculations off the main thread and return the result with postMessage.

JavaScript Preview
// 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
#javascript #web-worker #performance #frontend
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #238
Open
JavaScript
Public

Infinite Scroll with IntersectionObserver

Load the next page when a sentinel approaches the viewport and prevent duplicate requests.

JavaScript Preview
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];
#javascript #intersection-observer #infinite-scroll #performance
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #237
Open
TypeScript
Public

Typed JSON Fetch Helper

Wrap fetch with JSON parsing, typed responses, and useful HTTP error messages.

TypeScript Preview
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',
#typescript #fetch #api #json
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #235
Open
TypeScript
Public

Async Generator for Paginated API Data

Iterate through paginated API responses without loading every page into memory.

TypeScript Preview
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 {
#typescript #async #pagination #api
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #234
Open
JavaScript
Public

Process Mixed Results with Promise.allSettled

Run independent asynchronous tasks and keep both successful and failed outcomes.

JavaScript Preview
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()),
#javascript #promise #async #error-handling
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #233
Open
JavaScript
Public

URLSearchParams Filter State

Read, update, and remove page filters without manually concatenating query strings.

JavaScript Preview
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);
#javascript #urlsearchparams #filter #frontend
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #232
Open
TypeScript
Public

Next.js Route Handler with JSON Validation

Validate a JSON request body and return typed responses from an App Router Route Handler.

TypeScript Preview
// 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 {
#nextjs #route-handler #api #typescript
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #226
Open
TSX
Public

Online Status with useSyncExternalStore

Subscribe to the browser online state through React useSyncExternalStore.

TSX Preview
'use client';

import { useSyncExternalStore } from 'react';

function subscribe(callback: () => void) {
  window.addEventListener('online', callback);
  window.addEventListener('offline', callback);

  return () => {
#react #hooks #state #browser-api
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #219
Open
TSX
Public

Reusable useDebouncedValue Hook

Delay a rapidly changing value before triggering searches, validation, or API requests.

TSX Preview
'use client';

import { useEffect, useState } from 'react';

export function useDebouncedValue<T>(
  value: T,
  delay = 300,
): T {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
#react #hooks #debounce #utility
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #218
Open
PHP
Public

cURL GET Request in PHP

Call an external API with cURL and decode the JSON response.

PHP Preview
<?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 #curl #api #json
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #128
Open
PHP
Public

PHP Read JSON Request Body

Read and validate a JSON request body in PHP.

PHP Preview
<?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 #api #json #validation
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #127
Open
PHP
Public

PHP JSON Response Helper

Return a JSON response from a small PHP endpoint.

PHP Preview
<?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;
}
#php #api #json #response
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #126
Open
JavaScript
Public

Fetch POST JSON Request

Send JSON data to a backend endpoint with fetch.

JavaScript Preview
async function createNote(note) {
    const response = await fetch('/api/notes', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(note)
    });

    if (!response.ok) {
#api #javascript #post #json
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #125
Open
JavaScript
Public

Fetch GET Request

Load JSON from an API endpoint with async and await.

JavaScript Preview
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.');
    }
#api #javascript #fetch #json
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #124
Open
JavaScript
Public

Fetch JSON with Error Handling

Fetch JSON data and handle HTTP errors cleanly.

JavaScript Preview
async function loadProfile() {
    const response = await fetch('/api/profile');

    if (!response.ok) {
        throw new Error(`Request failed: ${response.status}`);
    }

    return await response.json();
}

loadProfile()
#javascript #fetch #json #error-handling
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #117
Open
PHP
Public

Safe HTML Escape Helper

A small PHP helper for escaping output in HTML templates.

PHP Preview
<?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>';
#php #security #xss #helper
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #73
Open
JavaScript
Public

Copy Text to Clipboard

A vanilla JavaScript helper to copy text to the clipboard with a fallback message.

JavaScript Preview
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;
  }
}
#javascript #clipboard #utility #beginner
CodShot user
CodShot user
Updated: 2026-06-03 14:05
Public snippets
0 #64
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support