Backend AI coding prompts work best when they describe the system behavior, the data rules, the failure cases, and the verification target — not just the endpoint you want generated.
A weak prompt says, “Build me an API.”
A strong prompt says, “Build a paginated REST API with authentication, input validation, consistent error responses, rate limiting, database indexes, and tests that prove the happy path and failure paths work.”
That difference matters. Backend code is where AI-generated apps usually hide the expensive mistakes: insecure auth, missing validation, fragile database logic, background jobs that retry dangerously, file uploads that trust the client, and deployment surprises that only appear after localhost is gone.
This guide gives you backend prompts you can copy, adapt, and run through Claude Code, Cursor, Copilot, ChatGPT, or any coding agent. If you want the broader prompt structure first, start with vibe coding prompts that actually work. If your backend is already built and you are trying to ship it, pair this with the vibe coding deployment checklist.
Do not ask an AI coding tool for “an API”. Ask for the API contract, data model, validation rules, security boundaries, failure behavior, and proof that it works.
What Makes a Backend Prompt Good?
A backend prompt needs more structure than a frontend prompt because the dangerous parts are often invisible.
A button that looks wrong is obvious. An auth flow that leaks whether an email exists is not. A file upload endpoint that trusts the MIME type might work perfectly in your demo and still be unsafe. A task queue that retries a payment job three times might look resilient while quietly creating a business problem.
Before asking an AI tool to build backend code, include these six pieces:
- Runtime and stack — Node, Express, Fastify, Next.js route handlers, Python, Postgres, Redis, etc.
- Data model — tables, entities, relationships, ownership rules, and indexes.
- API contract — endpoints, methods, request bodies, response shape, and status codes.
- Security rules — auth, roles, rate limits, secret handling, CSRF, token storage, and input validation.
- Failure behavior — expired tokens, duplicate records, invalid input, downstream outages, race conditions, and partial failures.
- Definition of done — tests, curl examples, build commands, migrations, or a working end-to-end flow.
If your prompt does not include those, the agent will fill in the blanks. Sometimes it fills them well. Sometimes it gives you a backend that is one demo away from embarrassing you.
Prompt 1: REST API With Authentication
Use this when you need a normal CRUD-style backend with real login/session behavior.
Build a production-grade authentication REST API in Node + TypeScript using Express or Fastify and PostgreSQL.
Endpoints:
- POST /auth/register
- POST /auth/login
- POST /auth/refresh
- POST /auth/logout
- GET /me
Requirements:
- Validate all request bodies with Zod.
- Hash passwords with bcrypt at cost 12.
- Use short-lived JWT access tokens.
- Use rotating refresh tokens stored hashed in the database.
- Send refresh tokens as HTTP-only, Secure, SameSite cookies.
- Keep access tokens out of localStorage.
- Add role-based access control for admin and user routes.
- Add per-route rate limiting.
- Return a consistent JSON error envelope: { data, error, meta }.
- Never leak stack traces or reveal whether an email exists.
Handle these edge cases:
- duplicate email registration
- expired access token
- malformed token
- refresh token reuse
- two browser tabs refreshing at the same time
- repeated failed logins
Structure the code into routes, controllers, services, repositories, middleware, and config. Include a migration for the users, sessions, and refresh token family tables.
Done when register → login → refresh → logout works end to end, refresh-token reuse revokes the session family, and tests prove invalid login responses do not reveal whether the email exists.
Why this works: it does not just ask for “auth.” It specifies token storage, cookie behavior, user enumeration, session rotation, table needs, and testable outcomes.
If the agent produces localStorage token storage or plain refresh tokens in the database, stop and correct it before moving on. That is not a polish issue. That is a security boundary.
Prompt 2: CRUD API With Pagination and Filtering
Use this for dashboards, admin tools, directories, content systems, inventory tools, and simple SaaS apps.
Build a CRUD REST API for a project task system in Node + TypeScript with Fastify and PostgreSQL.
Entities:
- projects: id, name, description, owner_id, created_at, updated_at
- tasks: id, project_id, title, description, status, priority, assignee_id, due_date, created_at, updated_at
- comments: id, task_id, author_id, body, created_at
Endpoints:
- GET /projects
- POST /projects
- GET /projects/:id
- PATCH /projects/:id
- DELETE /projects/:id
- GET /projects/:id/tasks
- POST /projects/:id/tasks
- PATCH /tasks/:id
- DELETE /tasks/:id
- POST /tasks/:id/comments
Requirements:
- Cursor pagination, not offset pagination, for task lists.
- Filters for status, priority, assignee, and due date range.
- Sort by created_at, due_date, or priority.
- All input validated with Zod.
- Only project members can read or mutate project data.
- Soft-delete projects and tasks.
- Add indexes that match the filter and sort patterns.
- Return consistent responses with data, error, and meta.
Include migration SQL, route handlers, service logic, and integration tests. Show example curl requests for creating a project, adding tasks, filtering tasks, and handling unauthorized access.
Done when filters compose correctly, unauthorized users cannot access another project, deleted tasks disappear from normal list responses, and the query plan uses indexes for the main list endpoint.
The key here is composability. A lot of AI-generated CRUD APIs work until you combine filters, sorting, pagination, and permissions. Ask for those combinations up front.
Prompt 3: File Upload Service
Use this when your app lets users upload images, PDFs, avatars, receipts, documents, or media.
Build a secure file upload API in Node + TypeScript using Fastify, PostgreSQL, and S3-compatible storage. Use MinIO locally behind a storage abstraction.
Features:
- Single and batch uploads.
- Maximum 10MB per file.
- Maximum 5 files per request.
- Allowed types: jpg, png, webp, pdf, docx.
- Validate file type by sniffing magic bytes, not by trusting extension or client MIME type.
- Stream uploads instead of buffering entire files in memory.
- Store metadata in Postgres: id, owner_id, original_name, storage_key, detected_mime, byte_size, checksum, created_at.
- Store objects under UUID or content-addressed keys.
- Return short-lived signed URLs for retrieval.
Security requirements:
- Sanitize original filenames.
- Reject path traversal attempts.
- Reject oversized streams early.
- Add an antivirus scan hook.
- Prevent SVG/script payloads unless explicitly supported and sanitized.
- Never expose raw bucket credentials to the client.
Reliability requirements:
- If database insert fails, delete the uploaded object.
- If object storage fails, do not create the database row.
- Return per-file success/failure results for batch uploads.
- Add tests for oversized files, spoofed MIME types, wrong extensions, and failed DB writes.
Done when valid uploads return working signed URLs, spoofed files are rejected before storage, and a failed database write never leaves an orphaned object in the bucket.
File uploads are one of the places where AI tools love the easy path. The easy path is usually wrong: trust the MIME type, store the original filename, read the whole thing into memory, and skip cleanup. This prompt blocks those mistakes.
Prompt 4: Background Job Queue
Use this for email, reports, image processing, webhook retries, scheduled tasks, and anything that should not block the request/response cycle.
Build a background job system in Node + TypeScript using BullMQ and Redis.
Job types:
- send_email
- generate_report
- process_image_upload
Requirements:
- Typed producers for each job type.
- Zod-validated payloads.
- Worker with configurable concurrency.
- Idempotency keys so retries do not duplicate side effects.
- Exponential backoff with jitter, max 3 attempts.
- Dead-letter queue for terminal failures.
- Structured logs with correlation IDs.
- Status endpoint: GET /jobs/health.
- Health response includes waiting, active, completed in the last hour, failed count, and failure rate.
- Graceful shutdown on SIGTERM.
- Stalled-job recovery.
- One repeatable scheduled job as an example.
Handle these failure cases:
- transient email provider outage
- permanent validation failure
- Redis connection loss
- SIGTERM while a job is running
- retry of a job that has already completed
Done when a transient failure retries and succeeds, a permanent failure lands in the dead-letter queue with its error preserved, SIGTERM loses no jobs, and the status endpoint reports accurate counts.
The important word is idempotency. If a job can run twice, the prompt needs to say what happens when it does. Otherwise the agent may build a retry system that turns one failure into three duplicate side effects.
Prompt 5: WebSocket or Real-Time Backend
Use this for chat, live dashboards, multiplayer features, collaboration, notifications, and presence.
Implement a real-time chat backend in Node + TypeScript using Socket.IO or ws, PostgreSQL for persistence, and Redis pub/sub so the system can run across multiple server instances.
Features:
- Multiple rooms.
- Join and leave notifications.
- Typing indicators.
- Online presence per room.
- Message history: last 50 messages on join with cursor pagination.
- Reconnection with missed-message backfill.
Security and correctness:
- Authenticate the socket handshake with the same JWT used by the REST API.
- Authorize room membership before a user can join.
- Persist every message before broadcast or clearly document the opposite ordering and tradeoff.
- Sanitize message content before rendering.
- Add message size limits.
- Add server-side rate limiting: max 10 messages per 10 seconds per user.
- Use idempotent client-supplied message IDs to avoid duplicate delivery.
- Clean up presence correctly on disconnect, heartbeat timeout, and server crash.
Done when two clients connected to different server instances can exchange messages, history loads correctly after reconnect, presence is accurate, and the flood limiter blocks abuse without dropping normal messages.
Real-time code often works in the single-tab demo and breaks the moment you add reconnects, duplicate messages, or multiple server instances. Make the prompt include those realities.
Prompt 6: GraphQL API With Resolvers
Use this when the client needs flexible nested data and you are willing to manage schema design, resolver performance, and query limits.
Set up a GraphQL API in Node + TypeScript using Apollo Server or GraphQL Yoga, backed by PostgreSQL.
Domain:
- User has many Posts.
- Post has many Comments.
- Comment belongs to User and Post.
Requirements:
- Define User, Post, and Comment types.
- Query a paginated post list.
- Query one post with nested comments.
- Search posts by title.
- Mutations to create, update, and delete posts.
- Zod-validate mutation inputs.
- Only the author or an admin may mutate a post.
- Use DataLoader batching for every nested association.
- Add query depth and cost limits.
- Return typed errors for validation, authorization, and not-found cases.
- Use schema-first codegen so resolver types are generated.
Handle edge cases:
- empty page
- invalid cursor
- stale cursor
- unauthorized mutation
- deleted post with existing comments
- deeply nested query attempting to overload the server
Done when fetching posts with authors and comments uses a bounded number of SQL queries, unauthorized mutations return a typed error, invalid cursors fail gracefully, and generated resolver types match the schema.
GraphQL can be powerful, but AI-generated GraphQL often misses the N+1 problem. If you ask for GraphQL, ask for batching, depth limits, and proof that nested queries do not explode.
Prompt 7: Rate Limiting Middleware
Use this when your API has public routes, login routes, free/pro tiers, expensive endpoints, or anything that can be abused.
Build configurable rate-limiting middleware in Node + TypeScript for Express or Fastify, backed by Redis so limits are shared across server instances.
Requirements:
- Support fixed window, sliding window, and token bucket strategies.
- Select strategy per route.
- Key limits by authenticated user when available.
- Fall back to client IP for anonymous requests.
- Parse IP only from trusted proxy headers; do not blindly trust X-Forwarded-For.
- Support tiered limits: free 60/min, pro 600/min.
- Support per-route overrides.
- Bypass health checks.
- Set response headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset.
- Return 429 with Retry-After when exceeded.
- Use atomic Redis operations so concurrent requests cannot race past the limit.
- Make Redis-down behavior configurable: fail open or fail closed.
Tests:
- concurrent requests at the limit
- anonymous IP fallback
- user-tier override
- per-route override
- Redis unavailable
- trusted proxy parsing
Done when concurrent requests never exceed the configured limit due to a race, headers match the actual limit state, and Redis-down behavior follows the configured policy.
This prompt is good because it asks for distributed behavior, not just a local counter. That matters when the app has more than one server process.
How To Use These Prompts Without Creating a Mess
Do not paste all seven prompts into one chat and ask the agent to build your backend in one heroic pass. That is how you get a giant code dump nobody understands.
Use the prompts in this order:
- Architecture pass: Ask the agent to read the repo and propose the file structure, data model, and implementation plan.
- Contract pass: Ask for endpoint definitions, request/response shapes, and database migrations.
- Implementation pass: Build one feature slice at a time.
- Verification pass: Run tests, curl the API, inspect logs, and check database state.
- Security pass: Review auth, secrets, validation, rate limits, and permissions.
- Deployment pass: Confirm environment variables, database migrations, start commands, and host compatibility.
That flow pairs well with AGENTS.md project instructions, a codebase knowledge graph, and focused AI coding subagents. The instructions define the rules. The graph helps the agent find the connected files. Subagents can review one bounded slice instead of wandering through the whole repo.
Backend Prompt Checklist
Before you run a backend prompt, check that it answers these questions:
- What stack should the agent use?
- What data model should it create or modify?
- What endpoints or job types are in scope?
- What should the response format look like?
- Who is allowed to do what?
- What validation is required?
- What should happen when something fails?
- What security mistake should the agent avoid?
- What test or command proves the feature works?
- What files should the agent not touch?
If you cannot answer those yet, do a planning prompt first. Backend work rewards boring clarity.
For backend work, “the code looks right” is not proof. Ask for tests, curl commands, migration checks, logs, and one real end-to-end flow.
Common Backend Prompt Mistakes
Asking for too much at once
“Build a SaaS backend” is not a prompt. It is a wish. Break the backend into authentication, users, billing, projects, permissions, jobs, and deployment.
Ignoring database constraints
If the database allows bad data, the app eventually creates bad data. Ask for foreign keys, unique constraints, checks, indexes, and explicit delete behavior.
Trusting the client
The client can lie about MIME type, user ID, role, price, quantity, URL, and anything else in the request. Backend prompts should say what the server validates independently.
Forgetting failure paths
A backend that only works when every service is healthy is not done. Include expired tokens, duplicate records, bad input, provider downtime, retry failure, and database errors.
Treating deployment as separate from design
A backend that uses local files, SQLite, or long-running sockets may not fit every host. Before you ship, read how to deploy a vibe-coded app and make sure your backend matches the platform.
FAQ
What is the best backend AI coding prompt?
The best backend AI coding prompt describes the runtime, API contract, data model, validation rules, permissions, failure cases, and proof of completion. A prompt that includes those details will beat a vague “build an API” request almost every time.
Can AI build a secure backend?
AI can help build secure backend code, but it needs clear constraints and human verification. Always review authentication, token storage, permissions, secrets, validation, and rate limits before real users touch the app.
Should I use Express, Fastify, or Next.js API routes?
Use the stack that matches the app. Express is familiar and common. Fastify is a strong API-focused choice. Next.js route handlers are convenient when the backend is part of a full-stack Next app. The prompt should name the target stack so the AI does not guess.
Are these prompts only for Node?
No. They are written in Node + TypeScript because many vibe-coded apps use that stack, but the structure transfers to Python, Go, Ruby, or PHP. Keep the contract, validation, security, failure handling, and proof sections.
Final Take
Backend prompts need to be boring in the best way.
They should name the stack, define the data, set the contract, block the obvious security mistakes, describe the weird failure cases, and demand proof. That is how you turn an AI coding assistant from a code generator into a useful backend partner.
Start with one feature. Make it work. Test it outside the app. Then move to the next slice.