10 Prompts for Building React/Next.js Apps: A Developer's Guide to AI-Assisted Frontend
Introduction
React and Next.js have become the backbone of modern frontend development. According to the 2025 Stack Overflow Developer Survey, React remains the most popular web framework, used by over 40% of professional developers. As AI coding assistants like GitHub Copilot and Claude become more powerful, the ability to craft precise prompts is a skill that separates productive developers from those who waste hours debugging generated code.
This article provides a curated collection of 10 ready-to-use prompts for building React components and Next.js pages. Each prompt is designed to produce production-ready code, with explanations and real-world examples. Whether you're building a dashboard, an e-commerce store, or a blog, these prompts will save you time and help you avoid common pitfalls.
1. Create a Reusable Button Component
Prompt:
Generate a reusable React Button component with the following requirements:
- Written in TypeScript
- Supports variant prop: 'primary', 'secondary', 'outline', 'ghost'
- Supports size prop: 'sm', 'md', 'lg'
- Supports loading state with a spinner
- Uses CSS modules for styling
- Includes a default export
- Follows accessibility best practices (aria-label, role, keyboard navigation)
Explanation: This prompt is perfect for creating a foundational UI component. By specifying TypeScript, variant/size props, loading state, and accessibility, you get a component that can be dropped into any React project. The use of CSS modules ensures scoped styling without conflicts.
Usage example: Paste the prompt into Claude or GPT-4, and you'll receive a Button.tsx file with a corresponding Button.module.css. The generated code typically includes a Spinner sub-component and proper event handling.
2. Build a Next.js API Route with Authentication
Prompt:
Create a Next.js API route for user authentication using JWT:
- Route: /api/auth/login
- Method: POST
- Accepts JSON body with email and password fields
- Validates input using zod
- Returns a JWT token on success (expires in 7 days)
- Returns 401 on invalid credentials
- Returns 400 on validation error
- Uses environment variables for JWT_SECRET
- Includes error logging to console
Explanation: This prompt generates a complete API endpoint. By specifying zod for validation, JWT for tokens, and environment variables, you ensure security best practices. Next.js API routes are serverless functions, so the code will be ready for deployment on Vercel or similar platforms.
Usage example: After running the prompt, you'll get a file at pages/api/auth/login.ts (or app/api/auth/login/route.ts for App Router). The generated code will include a zod schema and a handler function that uses jsonwebtoken.
3. Generate a Responsive Data Table with Sorting and Filtering
Prompt:
Generate a React DataTable component that:
- Accepts an array of objects with any shape
- Renders a responsive HTML table with sticky header
- Supports client-side sorting by clicking column headers
- Supports text-based filtering via an input field above the table
- Shows a loading skeleton state
- Shows an empty state message when no data matches
- Uses React hooks (useState, useMemo)
- Written in TypeScript with generic type for data rows
Explanation: Data tables are a common requirement in dashboards and admin panels. This prompt covers edge cases: loading, empty, and filtered states. The sticky header is crucial for large datasets, and the generic type makes the component reusable across different data shapes.
Usage example: The generated component can be used as <DataTable data={users} columns={['name', 'email', 'role']} />. The sorting logic uses useMemo for performance, and the filter input updates the displayed rows in real-time.
4. Create a Next.js Blog Page with MDX Support
Prompt:
Build a Next.js page that displays a list of blog posts from MDX files:
- Uses App Router (app directory)
- Reads .mdx files from a /content/posts folder
- Renders a grid of post cards with title, excerpt, date, and author
- Supports pagination (5 posts per page)
- Uses next/image for optimized images
- Includes a search bar that filters posts by title or excerpt
- Generates static pages at build time (generateStaticParams)
Explanation: MDX allows you to write content with embedded React components. This prompt generates a fully functional blog section with SEO-friendly static generation. The generateStaticParams function ensures all pages are pre-rendered, improving performance and SEO.
Usage example: Place your MDX files in content/posts, and the page will automatically list them. The search bar uses JavaScript to filter posts client-side, providing instant feedback without a page reload.
5. Generate a Custom Hook for Form Handling
Prompt:
Create a custom React hook called useForm that:
- Accepts an initial values object and a validation schema (zod)
- Returns: values, errors, touched, handleChange, handleBlur, handleSubmit, isValid, isSubmitting
- handleSubmit runs validation before calling an onSubmit callback
- Tracks touched fields for displaying errors only after blur
- Resets form to initial values on demand
- Written in TypeScript with generics for type safety
- Includes a use case example with email and password fields
Explanation: Form handling is repetitive. This hook replaces boilerplate code for validation, error display, and submission. By integrating zod, you get runtime type checking similar to libraries like React Hook Form, but custom-built.
Usage example: In a login component, you'd call const form = useForm({ email: '', password: '' }, loginSchema) and spread the returned handlers onto input elements. The isValid flag can disable the submit button until all fields pass validation.
6. Build a Next.js Middleware for Route Protection
Prompt:
Create a Next.js middleware that:
- Protects routes under /dashboard/*
- Checks for a valid JWT token in cookies
- If token is missing or expired, redirect to /login
- If token is valid, extract user role from payload
- Redirects users without 'admin' role away from /dashboard/admin
- Uses jose library for JWT verification (no need for jsonwebtoken)
- Logs failed access attempts to console
- Works with both App Router and Pages Router
Explanation: Middleware runs before a request is completed, making it ideal for authentication and authorization. The jose library is recommended because it's a pure JavaScript implementation that works in Edge Runtime, unlike jsonwebtoken which relies on Node.js crypto.
Usage example: Place the code in middleware.ts at the root of your project. The middleware will automatically run on every request matching the matcher config, redirecting unauthorized users before any page renders.
7. Generate a Modal Component with Portal
Prompt:
Create a React Modal component that:
- Uses ReactDOM.createPortal to render into document.body
- Supports open, onClose, title, and children props
- Closes on Escape key press
- Closes on overlay click
- Traps focus inside the modal for accessibility
- Includes a fade-in animation using CSS transitions
- Prevents body scroll when modal is open
- Written in TypeScript
Explanation: Modals are tricky because of z-index stacking, scroll prevention, and focus management. Using a portal ensures the modal renders outside the parent DOM hierarchy. Focus trapping is essential for screen reader users.
Usage example: Display a confirmation dialog: <Modal open={isOpen} onClose={() => setIsOpen(false)} title="Delete Item"><p>Are you sure?</p></Modal>. The body scroll lock and keyboard handling are built-in.
8. Create a Next.js Image Gallery with Lightbox
Prompt:
Build a Next.js image gallery component that:
- Takes an array of image URLs and alt texts
- Displays a grid of thumbnails using next/image
- Clicking a thumbnail opens a lightbox overlay
- Lightbox shows full-size image with next/previous navigation
- Supports keyboard arrows for navigation
- Shows image counter (e.g., '3 / 10')
- Includes a close button and overlay click to dismiss
- Uses CSS Grid for responsive layout
Explanation: Image galleries are common in portfolios and e-commerce. Using next/image provides automatic optimization, lazy loading, and responsive sizes. The lightbox pattern improves user experience without navigating away.
Usage example: Pass an array of image objects to the component. The lightbox opens with a smooth transition, and users can navigate using arrow buttons or keyboard. The counter helps users understand their position in the gallery.
9. Generate a Dashboard Layout with Sidebar
Prompt:
Create a Next.js dashboard layout that:
- Uses the App Router layout system (layout.tsx)
- Has a collapsible sidebar on the left with navigation links
- Sidebar includes icons from lucide-react
- Has a top header bar with user avatar and notifications bell
- Main content area fills remaining space
- Sidebar collapses to icons-only on screens < 768px
- Uses CSS variables for theming (light/dark mode ready)
- Includes a theme toggle button in the header
Explanation: Dashboards need consistent layouts. The App Router layout system means the sidebar only renders once, improving performance. CSS variables make it easy to add dark mode later. The collapsible sidebar is a standard UX pattern.
Usage example: Wrap your dashboard pages in this layout. The sidebar navigation items can be passed as props or defined in a config file. The theme toggle button updates a CSS class on the root element.
10. Build a Real-Time Chat Component with WebSockets
Prompt:
Generate a React real-time chat component that:
- Connects to a WebSocket server at ws://localhost:8080
- Shows a list of messages with sender name, timestamp, and text
- Has an input field and send button at the bottom
- Auto-scrolls to the latest message
- Shows a typing indicator when other users are typing
- Reconnects automatically on connection loss
- Displays connection status (connected/disconnected)
- Uses useRef for WebSocket instance and useCallback for handlers
- Written in TypeScript
Explanation: Real-time features like chat are increasingly common. This prompt covers connection management, reconnection logic, and the typing indicator pattern. Proper cleanup in useEffect prevents memory leaks.
Usage example: Mount the component in a Next.js page. The WebSocket connection starts when the component mounts and closes on unmount. Messages appear instantly, and the auto-scroll keeps the latest message visible.
Conclusion
AI-assisted development is not about replacing engineers—it's about accelerating the mundane parts of coding so you can focus on architecture, business logic, and user experience. The 10 prompts above cover the most common patterns in React and Next.js development: components, hooks, API routes, layouts, and real-time features.
To get the best results, always include constraints (TypeScript, framework version, styling approach) and edge cases (loading, empty, error states) in your prompts. Review generated code carefully—AI can produce efficient patterns but may miss nuances of your specific project setup. For integrations with external services like authentication providers, ASI Biont supports connecting to APIs via webhooks and custom endpoints—learn more at asibiont.com/courses.
Start using these prompts today, and you'll see a noticeable improvement in your development speed and code quality.
Comments