Explore

Explore snippets

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

Public snippets by CodShot user
Clear
18 public snippets
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
TSX
Public

Parallel Data Fetching in a Server Component

Start independent server requests together to reduce total rendering time.

TSX Preview
// app/dashboard/page.tsx

async function getUser() {
  return db.user.findFirst();
}

async function getRecentOrders() {
  return db.order.findMany({
    orderBy: {
      createdAt: 'desc',
    },
    take: 5,
  });
}
#nextjs #server-components #async #performance
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #230
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
TSX
Public

Next.js Loading Skeleton

Provide instant loading UI for an App Router segment with loading.tsx.

TSX Preview
// 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">
#nextjs #suspense #loader #ui
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #228
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
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

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
TSX
Public

React Form Validation with useActionState

Manage form validation, submission status, and server-style action results with React useActionState.

TSX Preview
'use client';

import { useActionState } from 'react';

type FormState = {
  message: string;
  errors: {
    email?: string;
  };
};

const initialState: FormState = {
  message: '',
  errors: {},
};

async function subscribe(
  previousState: FormState,
#react #hooks #form #validation
CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0 #211
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
HTML / Markup
Public

Bootstrap Modal Form Skeleton

A small Bootstrap 5 modal with a form and submit button.

HTML / Markup Preview
<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">
#bootstrap #modal #form #ui
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #120
Open
JavaScript
Public

Simple Form Validation

Validate a small form before submitting it.

JavaScript Preview
const form = document.querySelector('#contactForm');
const emailInput = document.querySelector('#email');
const messageBox = document.querySelector('#formMessage');

form.addEventListener('submit', (event) => {
    messageBox.textContent = '';
#javascript #form #validation #frontend
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #116
Open
PHP
Public

Basic Upload Validation

Validate upload error, size, and MIME type before accepting a file.

PHP Preview
<?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.');
}
#php #upload #validation #security
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #113
Open
PHP
Public

Safe Redirect Allow List

Redirect only to known internal paths instead of trusting user input.

PHP Preview
<?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;
#php #redirect #security #validation
CodShot user
CodShot user
Updated: 2026-06-08 14:33
Public snippets
0 #112
Open
Regex
Public

Match Date YYYY-MM-DD

Match a simple ISO-style date format.

Regex Preview
^\d{4}-\d{2}-\d{2}$
#regex #date #validation #format
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #98
Open
Regex
Public

Validate Hex Color

Match CSS hex colors like #fff or #a1b2c3.

Regex Preview
^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$
#regex #css #color #validation
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #96
Open
Regex
Public

Match Email Address

A practical beginner regex for basic email-like text matching.

Regex Preview
^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$
#regex #email #validation #beginner
CodShot user
CodShot user
Updated: 2026-06-03 15:31
Public snippets
0 #94
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