AI Coding Prompts

50 professional, copy-ready vibe coding prompts for building real software with AI. Click any prompt to copy it to your clipboard.

#01 Frontend

Responsive Dashboard Layout

Build a responsive admin dashboard layout with a collapsible sidebar navigation, a top header bar with search and user avatar, and a main content area that displays a grid of stat cards. Use CSS Grid for the overall layout and Flexbox for component alignment. The sidebar should collapse to icons only on tablet and hide behind a hamburger menu on mobile. Use semantic HTML5 elements throughout.

#02 Frontend

Accessible Form with Validation

Create a multi-step registration form with client-side validation. Include fields for personal info (name, email, phone), account setup (username, password with strength meter), and preferences (checkboxes, radio buttons, select dropdowns). Each step should validate before allowing progression. Use ARIA labels, live error regions, focus management on step transitions, and keyboard navigation. Style with a clean, modern look using CSS custom properties.

#03 Frontend

Animated Card Carousel

Build a horizontal card carousel component that supports touch swipe gestures on mobile, keyboard arrow navigation, and click/drag on desktop. Cards should snap into position with smooth CSS transitions. Include pagination dots and previous/next arrow buttons. The carousel should be responsive — show 3 cards on desktop, 2 on tablet, 1 on mobile. Use no external libraries, only vanilla JavaScript and CSS transforms.

#04 Frontend

Dark Mode Theme Switcher

Implement a complete dark/light mode system using CSS custom properties. Create a toggle button that switches themes with a smooth crossfade transition. Persist the user's preference in localStorage and respect the system's prefers-color-scheme on first visit. Define a full color palette for both themes including background, surface, text, accent, border, and shadow values. Ensure all interactive elements have appropriate hover and focus states in both themes.

#05 Frontend

Infinite Scroll Feed

Build an infinite scroll content feed that loads items as the user scrolls down. Use the Intersection Observer API to detect when the user approaches the bottom of the list. Display a loading skeleton placeholder while new items are being fetched. Include a "Back to top" floating button that appears after scrolling past the first viewport. Handle edge cases: empty states, error states with retry, and end-of-content messaging. Implement smooth scroll restoration on navigation.

#06 Frontend

Interactive Data Table

Create a data table component with sortable columns, text search filtering, pagination controls, and row selection with checkboxes. Clicking a column header should toggle between ascending, descending, and unsorted states with visual indicators. The search input should debounce and highlight matching text in cells. Pagination should show page numbers with ellipsis for large datasets. Include a bulk actions toolbar that appears when rows are selected. Make the table horizontally scrollable on small screens.

#07 Frontend

Micro-interaction Button Library

Design a set of 8 button variants with polished micro-interactions: primary (ripple effect on click), secondary (border draw-in on hover), ghost (background fade), danger (shake animation for destructive confirm), loading (spinner replacing text with smooth transition), success (checkmark morph after action), icon button (scale + rotate on hover), and toggle (sliding background with state change). Use CSS animations and minimal JavaScript. Each button should have accessible focus-visible outlines.

#08 Backend

REST API with Authentication

Build a REST API with user authentication using Node.js and Express. Include routes for user registration (with email validation and password hashing using bcrypt), login (returning JWT access and refresh tokens), token refresh, and logout (token blacklisting). Add middleware for JWT verification, role-based access control (admin, user, guest), and rate limiting per endpoint. Structure the code with separate route, controller, middleware, and utility layers. Include proper error handling with consistent JSON error responses.

#09 Backend

File Upload Service

Create a file upload API endpoint that handles multipart form data. Support single and batch file uploads with the following constraints: max file size of 10MB, allowed types (images: jpg/png/webp, documents: pdf/docx), and max 5 files per request. Generate unique filenames, create thumbnails for images using sharp, store metadata (original name, size, mime type, upload date) in the database, and return signed URLs for access. Include virus scanning middleware and cleanup of orphaned files.

#10 Backend

WebSocket Real-Time Chat

Implement a real-time chat server using WebSockets (ws or Socket.IO). Support multiple chat rooms, user join/leave notifications, typing indicators, message history (last 50 messages loaded on join), and online user presence. Messages should be persisted to a database. Include connection heartbeat monitoring, automatic reconnection handling on the client side, and graceful connection cleanup. Add rate limiting to prevent message flooding (max 10 messages per 10 seconds per user).

#11 Backend

Task Queue with Job Processing

Build a background job processing system using a task queue (BullMQ with Redis or a similar pattern). Create a job producer that enqueues tasks like sending emails, generating reports, and processing image uploads. Implement a worker that processes jobs with configurable concurrency, automatic retries with exponential backoff (max 3 attempts), and dead letter queue for failed jobs. Add a simple status API endpoint that returns queue health: pending count, active jobs, completed in last hour, and failure rate.

#12 Backend

GraphQL API with Resolvers

Set up a GraphQL API server with type definitions and resolvers for a blog platform. Define types for User, Post, and Comment with their relationships (User has many Posts, Post has many Comments). Implement queries for listing posts with pagination (cursor-based), fetching a single post with nested comments, and searching posts by title. Add mutations for creating, updating, and deleting posts with input validation. Include a DataLoader implementation to solve the N+1 query problem on nested fields.

#13 Backend

OAuth2 Social Login Integration

Implement OAuth2 social login supporting Google and GitHub providers. Create the full authorization code flow: redirect to provider, handle callback with code exchange, fetch user profile, and create or link local account. Store provider tokens securely, handle account linking when a user signs in with a different provider but the same email, and implement token refresh for expired provider tokens. Include CSRF protection using the state parameter and PKCE for public clients.

#14 Backend

API Rate Limiter Middleware

Build a flexible API rate limiting middleware with multiple strategies: fixed window (100 requests per minute), sliding window log (more accurate tracking), and token bucket (burst-friendly). Store rate limit state in Redis for distributed environments. Return standard rate limit headers (X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset) on every response. Support different limits per route and per user tier (free: 60/min, pro: 600/min). Include IP-based fallback for unauthenticated requests and a bypass mechanism for health check endpoints.

#15 Full-Stack

Project Management Board

Build a Kanban-style project management board (like Trello). Frontend: draggable cards between columns (To Do, In Progress, Review, Done) with smooth animations, card detail modal with title, description, assignee, labels, and due date. Backend: REST API for boards, columns, and cards with CRUD operations and position tracking for drag reorder. Use optimistic updates on the frontend — update the UI immediately on drag and sync with the server in the background. Include user assignment and filtering by assignee or label.

#16 Full-Stack

E-Commerce Product Catalog

Create a product catalog with category filtering, price range slider, search with autocomplete, and grid/list view toggle. Each product card shows image, title, price, rating stars, and an "Add to Cart" button. Implement a persistent shopping cart stored in localStorage that syncs with a backend cart API when the user is authenticated. Include product detail pages with image gallery, specifications table, and related products. Backend should serve paginated product data with filter query parameters.

#17 Full-Stack

User Dashboard with Analytics

Build a user dashboard that displays activity analytics. Frontend: chart components showing line graph (activity over time), bar chart (category breakdown), and a donut chart (completion rate). Use SVG or Canvas for charts — no chart libraries. Include date range picker to filter data, exportable as CSV. Backend: API endpoints that aggregate user activity data with grouping by day/week/month, calculate trends (percentage change from previous period), and return formatted time-series data. Cache aggregated results with a 5-minute TTL.

#18 Full-Stack

Bookmark Manager App

Build a bookmark manager where users can save, organize, and search their bookmarks. Frontend: clean card grid showing bookmark title, favicon, description (auto-fetched from URL metadata), and tags. Support folder organization with drag-and-drop, bulk tagging, and full-text search across title, URL, description, and tags. Backend: API for CRUD operations on bookmarks and folders, a URL metadata scraper that extracts title, description, and favicon from saved URLs, and tag-based filtering with AND/OR logic.

#19 Full-Stack

Real-Time Polling App

Create a live polling application where users can create polls with multiple options, share a link, and see results update in real time. Frontend: poll creation form with dynamic option fields, shareable poll page with animated bar chart showing live percentages, and a results view with total votes and timestamps. Backend: API for poll CRUD, vote submission with duplicate prevention (cookie + fingerprint based for anonymous polls), and WebSocket or Server-Sent Events to push vote updates to all connected viewers.

#20 Full-Stack

Markdown Note-Taking App

Build a note-taking application with live Markdown preview. Frontend: split-pane editor with Markdown input on the left and rendered HTML preview on the right that updates as you type. Include a toolbar with formatting buttons (bold, italic, heading, link, code block, list). Support note organization with folders, tagging, and starred/favorites. Backend: API for notes CRUD with auto-save (debounced PATCH requests), full-text search across note content, and export to Markdown or HTML file.

#21 Full-Stack

URL Shortener Service

Build a full URL shortener service. Frontend: input field for long URLs, custom alias option, expiration date picker, and a dashboard showing all shortened URLs with click analytics (total clicks, clicks over time chart, top referrers, geographic distribution). Backend: API that generates short codes (base62 encoding), redirects with 301 status, tracks click events with metadata (timestamp, user agent, referrer, IP-based geolocation), and provides analytics endpoints. Include rate limiting on URL creation and validation against malicious URLs.

#22 Debugging

Performance Profiling Audit

Analyze this code for performance issues. Look for: unnecessary re-renders or recomputations, missing memoization opportunities, expensive operations inside loops or hot paths, memory leaks from event listeners or subscriptions not being cleaned up, synchronous blocking operations that should be async, and inefficient data structures or algorithms. For each issue found, explain the problem, its impact, and provide the optimized version with comments explaining the improvement. Prioritize fixes by estimated performance impact.

#23 Debugging

Error Handling Hardening

Review this code and add comprehensive error handling. For each function: identify all possible failure points (network errors, null/undefined access, type mismatches, file system errors, database connection failures), add appropriate try-catch blocks with specific error types, implement graceful degradation where possible, add meaningful error messages that include context (function name, input parameters, operation being attempted), and ensure errors propagate correctly up the call stack. Never silently swallow errors.

#24 Debugging

Memory Leak Detective

Investigate this application for memory leaks. Check for: event listeners added but never removed, setInterval/setTimeout without cleanup, closures holding references to large objects, DOM nodes removed from the tree but still referenced in JavaScript, growing arrays or maps that are never pruned, circular references preventing garbage collection, and unclosed database connections or file handles. For each leak found, explain the mechanism, show how to reproduce it, and provide the fix with a before/after comparison.

#25 Debugging

Legacy Code Refactoring Plan

Analyze this legacy code and create a step-by-step refactoring plan. First, identify code smells: duplicated logic, god functions (over 50 lines), deeply nested conditionals (3+ levels), magic numbers and strings, tight coupling between modules, and inconsistent naming conventions. Then provide a prioritized refactoring plan where each step is small, safe, and independently deployable. For each refactoring step, show the before and after code and explain what was improved. Ensure no behavior changes — purely structural improvements.

#26 Debugging

Race Condition Finder

Audit this code for race conditions and concurrency bugs. Look for: shared mutable state accessed from multiple async operations, missing locks or semaphores on critical sections, time-of-check to time-of-use (TOCTOU) vulnerabilities, uncoordinated database read-modify-write cycles, UI state updates that can interleave incorrectly, and event handlers that assume sequential execution. For each issue, explain the race condition scenario step by step, show how it can produce incorrect results, and provide the fix using appropriate synchronization patterns.

#27 Debugging

Security Vulnerability Scan

Perform a security audit on this code. Check for OWASP Top 10 vulnerabilities: SQL injection (parameterized queries), XSS (output encoding, Content Security Policy), CSRF (token validation), broken authentication (password hashing, session management), sensitive data exposure (secrets in code, unencrypted data), insecure deserialization, and missing access controls. For each vulnerability found, classify its severity (critical/high/medium/low), explain the attack vector with a concrete example, and provide the secure implementation fix.

#28 Database

Multi-Tenant SaaS Schema

Design a PostgreSQL database schema for a multi-tenant SaaS application. Include tables for: organizations (tenant isolation), users (with roles per organization), subscriptions (plan tiers with feature flags), and audit logs (who changed what and when). Implement row-level security policies for tenant isolation. Add indexes optimized for common queries: user lookup by email within an org, subscription status checks, and audit log filtering by date range and actor. Include migration SQL for creating the schema with proper constraints, defaults, and comments.

#29 Database

Query Optimization Toolkit

Analyze these slow database queries and optimize them. For each query: run EXPLAIN ANALYZE and interpret the execution plan, identify full table scans, nested loops, and sort operations that could be improved. Suggest specific indexes (B-tree, GIN, partial, composite) with CREATE INDEX statements. Rewrite queries to use CTEs or subqueries where appropriate, eliminate N+1 patterns with JOINs or lateral joins, and apply pagination correctly using keyset pagination instead of OFFSET. Show before/after query plans with estimated performance improvement.

#30 Database

Data Migration Pipeline

Write a data migration script that transforms and moves data from a legacy schema to a new normalized schema. The migration should: run in batches (1000 rows at a time) to avoid locking, maintain referential integrity by migrating parent tables first, handle data cleaning (trim whitespace, normalize emails to lowercase, parse inconsistent date formats), log progress with estimated time remaining, support resuming from the last successful batch if interrupted, and validate row counts and checksums after completion. Include a dry-run mode that reports what would change without modifying data.

#31 Database

Redis Caching Layer

Implement a Redis caching layer for a database-backed API. Create a cache-aside pattern with: automatic cache population on miss, configurable TTL per entity type (users: 5 min, products: 1 hour, config: 24 hours), cache invalidation on write operations (update and delete), cache warming on application startup for hot data, and namespace-based bulk invalidation (clear all user caches when permissions change). Include connection pooling, graceful fallback to database when Redis is unavailable, and metrics tracking (hit rate, miss rate, average latency).

#32 Database

Full-Text Search Implementation

Implement full-text search for a content platform using PostgreSQL's built-in text search. Create a tsvector column with weighted fields (title: A, tags: B, body: C), a GIN index for fast lookups, and a search function that supports: phrase matching, prefix matching for autocomplete, typo tolerance using trigram similarity (pg_trgm), result ranking by relevance with ts_rank_cd, and highlighted search result snippets using ts_headline. Include a search suggestions endpoint that returns top 5 completions as the user types.

#33 DevOps

Docker Multi-Stage Build

Write a production-optimized Dockerfile for a Node.js application using multi-stage builds. Stage 1 (builder): install all dependencies and compile TypeScript. Stage 2 (production): copy only compiled output and production dependencies. Use a minimal base image (node:alpine), run as a non-root user, include health check endpoint, set proper signal handling for graceful shutdown (SIGTERM/SIGINT), add labels for metadata, and configure environment-specific settings via build args. Include a docker-compose.yml with the app service, PostgreSQL, Redis, and a reverse proxy with proper networking and volume configuration.

#34 DevOps

CI/CD Pipeline Configuration

Create a GitHub Actions CI/CD pipeline with the following stages. CI: checkout, cache dependencies (node_modules), install, lint (ESLint), type check (TypeScript), run unit tests with coverage reporting, and run integration tests against a PostgreSQL service container. CD: build Docker image, push to container registry with semantic version tagging, deploy to staging automatically on main branch push, and deploy to production on release tag with manual approval gate. Include status badges, Slack notifications on failure, and artifact retention for test reports.

#35 DevOps

Infrastructure as Code Setup

Write Terraform configuration to provision a production web application stack on AWS. Include: VPC with public and private subnets across 2 availability zones, an Application Load Balancer with HTTPS (ACM certificate), ECS Fargate service running the application container with auto-scaling (CPU/memory based, min 2 max 10 tasks), RDS PostgreSQL instance in private subnet with automated backups, ElastiCache Redis cluster, S3 bucket for file storage with lifecycle policies, and CloudWatch alarms for key metrics. Use modules for reusability and tfvars files for environment separation.

#36 DevOps

Monitoring and Alerting Stack

Set up a monitoring and alerting system for a production application. Configure: structured JSON logging with correlation IDs for request tracing, application metrics (request rate, error rate, response time percentiles, active connections), system metrics (CPU, memory, disk, network), health check endpoints (liveness and readiness probes), and alert rules with thresholds — error rate above 5% for 5 minutes (critical), p95 latency above 2 seconds (warning), disk usage above 80% (warning). Include a dashboard configuration showing the four golden signals: latency, traffic, errors, and saturation.

#37 DevOps

Zero-Downtime Deployment Script

Write a deployment script that performs zero-downtime deployments using blue-green strategy. The script should: pull the new image, start new containers (green) alongside current ones (blue), run health checks against green containers (HTTP 200 on /health with timeout), gradually shift traffic from blue to green using a load balancer (10%, 50%, 100% over 5 minutes), monitor error rates during rollout with automatic rollback if errors exceed threshold, drain connections on blue containers gracefully, and clean up old containers after successful deployment. Include detailed logging at each step and a manual rollback command.

#38 Testing

Unit Test Suite for API Service

Write a comprehensive unit test suite for a user service module. Test the following functions: createUser (valid input, duplicate email, password hashing, required field validation), getUserById (existing user, non-existent user, invalid ID format), updateUser (partial updates, email uniqueness on change, unauthorized access), and deleteUser (soft delete, cascade effects, admin-only access). Use Jest with proper setup/teardown, mock the database layer, test both success and error paths, verify function arguments passed to mocks, and assert specific error types and messages. Aim for 100% branch coverage.

#39 Testing

Integration Tests with Test Database

Set up integration tests that run against a real test database. Configure: a test database that is created before the test suite and destroyed after, migrations that run before all tests, seed data loaded before each test file, and transactions that roll back after each individual test for isolation. Write integration tests for the complete user registration flow: POST to create user, verify database record, attempt duplicate registration (expect 409), login with new credentials (expect JWT), and access a protected endpoint with the returned token. Use supertest for HTTP assertions.

#40 Testing

E2E Tests for User Flows

Write end-to-end tests using Playwright for critical user flows. Test 1 — Sign up flow: navigate to registration page, fill form fields, submit, verify redirect to dashboard, and confirm welcome email was triggered. Test 2 — Login and session: log in with valid credentials, verify dashboard loads, refresh page and verify session persists, log out and verify redirect to home. Test 3 — Create and edit content: log in, create a new post with title and body, verify it appears in the post list, edit the post, verify changes are saved. Include page object model pattern, screenshot on failure, and retry logic for flaky network assertions.

#41 Testing

API Contract Tests

Write API contract tests that verify the request/response shapes of every endpoint match the documented schema. For each endpoint: validate response status codes for success and error cases, verify response body matches the JSON schema (required fields, types, formats), test Content-Type headers, verify pagination envelope structure (data array, total count, next/prev cursors), and assert that error responses follow the standard format (code, message, details array). Use a schema validation library and generate the test cases from an OpenAPI spec if available. Include tests for edge cases: empty results, maximum pagination limits, and malformed request bodies.

#42 Testing

Component Tests with Mock Data

Write component tests for a React ProductCard component using React Testing Library. Test: renders product name, price (formatted as currency), and image with correct alt text; "Add to Cart" button fires callback with product ID and quantity; disabled state shows "Out of Stock" and prevents clicks; loading skeleton renders when isLoading prop is true; truncates long product names with ellipsis after 2 lines; sale price shows original price with strikethrough and sale price highlighted. Use a factory function to generate test product data with sensible defaults and easy overrides.

#43 Testing

Snapshot and Visual Regression Tests

Set up visual regression testing for a component library. Configure: a test runner that captures screenshots of each component in its various states (default, hover, focus, disabled, loading, error), compare against baseline images with a configurable diff threshold (0.1%), generate an HTML report showing side-by-side comparisons for any diffs, and update baselines with a single command. Write tests for 5 core components: Button (6 variants), Input (4 states), Card (with/without image), Modal (open/closed), and Toast (4 severity levels). Include responsive breakpoint screenshots at 375px, 768px, and 1440px widths.

#44 UI/UX

Design System Foundations

Create the CSS foundation for a design system using custom properties. Define: a type scale (8 sizes from xs to 4xl using a modular scale ratio of 1.25), spacing scale (4px base with 8 steps), color system with semantic tokens (background, surface, text-primary, text-secondary, accent, success, warning, error — each with light/dark mode values), border radius tokens (sm, md, lg, pill), shadow tokens (sm, md, lg, xl for elevation levels), and transition tokens (duration and easing for micro-interactions). Include a utility class system for spacing, typography, and display. Document each token with comments.

#45 UI/UX

Accessible Modal Dialog

Build a fully accessible modal dialog component. Requirements: focus is trapped inside the modal when open (Tab and Shift+Tab cycle through focusable elements), Escape key closes the modal, clicking the backdrop closes it, opening the modal moves focus to the first focusable element (or the close button), closing restores focus to the trigger element, background content has aria-hidden="true" and is inert, the modal has role="dialog", aria-modal="true", and aria-labelledby pointing to the title. Include smooth open/close animations that respect prefers-reduced-motion. Prevent body scroll when the modal is open.

#46 UI/UX

Skeleton Loading States

Create a skeleton loading system that matches the layout of the actual content. Build skeleton components for: a card (image placeholder, 2 text lines, metadata line), a data table (header row + 5 body rows with varying column widths), a user profile (avatar circle, name, bio lines, stats row), and a form (label + input pairs, textarea, button). Each skeleton should use a shimmer animation (gradient sweep from left to right). The shimmer should be a shared CSS animation so all skeletons pulse in sync. Include a Skeleton wrapper component that accepts a loading boolean and swaps between skeleton and actual content.

#47 UI/UX

Toast Notification System

Build a toast notification system that supports 4 types: success (green), error (red), warning (amber), and info (blue). Toasts should: appear in the top-right corner, stack vertically with newest on top, auto-dismiss after a configurable duration (default 5 seconds), pause the dismiss timer on hover, have a close button, support an optional action button (like "Undo"), animate in from the right and fade out on dismiss, and limit the maximum visible count to 5 (queue additional toasts). Provide a simple API: showToast({ type, message, duration, action }).

#48 UI/UX

Responsive Navigation Patterns

Build 3 responsive navigation patterns that switch between desktop and mobile layouts. Pattern 1 — Top navbar: horizontal links on desktop, hamburger menu with slide-in drawer on mobile, with animated hamburger-to-X icon transition. Pattern 2 — Sidebar navigation: persistent sidebar on desktop (260px), overlay drawer on tablet, bottom tab bar on mobile (5 icons max). Pattern 3 — Mega menu: multi-column dropdown on desktop hover, full-screen accordion on mobile touch. Each pattern should include smooth transitions, keyboard navigation, proper ARIA attributes, and focus management. Use no JavaScript frameworks.

#49 UI/UX

Scroll-Driven Animations

Implement a set of scroll-driven animations using the Intersection Observer API and CSS. Create: fade-up on enter (elements rise 20px and fade in when scrolled into view), staggered list reveal (list items animate in one by one with 100ms delay), parallax hero (background image moves at 50% scroll speed), progress bar in header (grows from 0% to 100% width as user scrolls through the page), and counter animation (numbers count up from 0 to target value when visible). All animations should respect prefers-reduced-motion by falling back to instant display. Include configurable thresholds and root margins.

#50 UI/UX

Empty State and Error Illustrations

Design a set of 5 empty state and error page layouts using pure CSS illustrations (no images). Create: "No results found" (magnifying glass with empty page), "Inbox zero" (open envelope with checkmark), "404 Not Found" (broken link chain), "Connection error" (disconnected plug), and "Under construction" (traffic cone with stripes). Each layout should include the illustration, a clear heading, a descriptive subtitle, and a primary action button. Use CSS shapes, gradients, and pseudo-elements for the illustrations. Keep the style minimal and consistent with a dark theme.

Need More Prompts?

We're building the largest open source library of AI coding prompts. Join the list to get notified when new prompts drop.