Explore

Explore snippets

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

Public snippets by CodShot user
Clear
20 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

TypeScript Discriminated Union Reducer

Model reducer actions safely with exhaustive TypeScript checking.

TypeScript Preview
type State = {
  count: number;
  label: string;
};

type Action =
  | {
      type: 'increment';
      amount: number;
    }
  | {
      type: 'rename';
      label: string;
    }
  | {
      type: 'reset';
    };

export function reducer(
  state: State,
#typescript #reducer #state #validation
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #236
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

Abortable Fetch with Timeout

Cancel a slow fetch request with AbortController while preserving the caller signal.

TypeScript Preview
type FetchWithTimeoutOptions = RequestInit & {
  timeoutMs?: number;
};

export async function fetchWithTimeout(
  input: RequestInfo | URL,
  options: FetchWithTimeoutOptions = {},
): Promise<Response> {
  const {
    timeoutMs = 8000,
#typescript #fetch #abortcontroller #error-handling
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #231
Open
TSX
Public

Next.js Route Error Boundary

Handle uncaught route segment errors and let the user retry without a full reload.

TSX Preview
// 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) {
#nextjs #error-handling #app-router #typescript
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #229
Open
TypeScript
Public

Dynamic Metadata with generateMetadata

Generate page-specific SEO metadata from a dynamic App Router route.

TypeScript Preview
// 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,
#nextjs #seo #meta #typescript
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #227
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
TypeScript
Public

Revalidate a Next.js Cache Tag after Mutation

Mark tagged data stale after a Server Action changes the underlying records.

TypeScript Preview
// 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,
    },
  });
#nextjs #revalidation #server-actions #caching
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #225
Open
TypeScript
Public

Next.js Cached Data with use cache

Cache a server data function and attach a reusable invalidation tag.

TypeScript Preview
// 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,
    },
#nextjs #caching #server-components #typescript
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #224
Open
TypeScript
Public

Next.js Proxy Authentication Guard

Redirect unauthenticated requests from protected routes with the Next.js proxy convention.

TypeScript Preview
// 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) {
#nextjs #proxy #auth #security
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #223
Open
TSX
Public

Next.js Server Action Form with useActionState

Connect a Next.js Server Action to a client form with validation and pending state.

TSX Preview
// app/actions.ts
'use server';

export type CreateUserState = {
  message: string;
  errors: {
    email?: string;
  };
};

export async function createUser(
  previousState: CreateUserState,
  formData: FormData,
): Promise<CreateUserState> {
#nextjs #server-actions #form #typescript
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #222
Open
TSX
Public

React Error Boundary Component

Catch rendering errors in a subtree and provide a retryable fallback UI.

TSX Preview
import {
  Component,
  type ErrorInfo,
  type ReactNode,
} from 'react';

type Props = {
  children: ReactNode;
  fallback?: ReactNode;
};

type State = {
  hasError: boolean;
};

export class ErrorBoundary extends Component<Props, State> {
  state: State = {
#react #error-handling #ui #typescript
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #221
Open
TSX
Public

Typed Context Reducer Pattern

Combine React context and useReducer with typed actions and a safe custom hook.

TSX Preview
'use client';

import {
  createContext,
  type ReactNode,
  useContext,
  useReducer,
} from 'react';

type CartState = {
  itemCount: number;
};

type CartAction =
  | { type: 'add'; quantity: number }
  | { type: 'clear' };
#react #context #reducer #typescript
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #220
Open
TSX
Public

Accessible Form Fields with useId

Generate stable IDs for reusable form controls and accessible help text.

TSX Preview
import { useId } from 'react';

type TextFieldProps = {
  label: string;
  name: string;
  helpText?: string;
};

export function TextField({
  label,
  name,
  helpText,
}: TextFieldProps) {
  const inputId = useId();
  const helpId = `${inputId}-help`;
#react #accessibility #form #typescript
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #215
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