Back to cookbook

Secure API Request Handler

16 views Published

Make this prompt yours

Share

A prompt that makes the model write an API route the way a security-conscious reviewer would want it: validated input, safe data access, uniform errors.

Because the requirements are listed as a checklist, the model addresses each one instead of producing a happy-path handler that trusts the request body.

Prompt template

Make this prompt yours

prompt-template
118 tokens
Write a Node.js Express route handler for a [METHOD] request to '[PATH]'. Requirements: - Validate the body with Zod: [FIELDS AND CONSTRAINTS]. - Use parameterized queries / the ORM only. No string-concatenated SQL. - Wrap the logic in try/catch. - Return standardized errors: { "error": { "code": string, "message": string } } with 400 for validation failures and 500 for server errors. Never leak stack traces. - Add a short comment above any security-relevant line. Return only the code.

Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.

Example input

example-input
33 tokens
Method: POST Path: /api/users Fields: email (valid email), name (2-60 chars), age (optional int 13-120)

When to use it

  • Adding a new endpoint to an Express or Fastify service
  • Generating boilerplate you will then review and tighten
  • Teaching juniors what a defensive handler looks like
  • Standardizing error shapes across a codebase

Best practices

  • Specify the validation library and the exact fields and constraints.
  • Ask for parameterized queries or an ORM, never string-built SQL.
  • Define the error response shape once and reuse it.
  • Always review generated auth and rate-limit code before shipping.

Common mistakes

  • Assuming generated code is secure without review or tests.
  • Not mentioning authentication, so the route is open by default.
  • Returning raw error messages that leak internals.

FAQs

Is the generated code production ready?

Treat it as a strong first draft. Review authentication, authorization and rate limiting, and add tests.

Can I use it for Next.js route handlers?

Yes. Change the first line to "Next.js App Router route handler" and ask for NextResponse returns.

Does Zod prevent SQL injection?

No. Zod validates shape. Injection is prevented by parameterized queries or an ORM, which is why the template requires both.

Found this prompt useful? Share it.

Share

More in Engineering

Engineering

AI Prompt to Write a Feature Flag Rollout and Cleanup Plan

A feature flag rollout plan lays out how a new capability ships behind a flag, moves through stages of exposure, and eventually gets removed…

You are a senior platform engineer helping plan a feature flag rollout.

Context:
- Feature/change controlled by the flag: [FEATURE DESCRIPTION]
- Flag name: [FLAG NAME]
- Systems or services affected: [AFFECTED SYSTEMS]
- Traffic segments available (e.g. internal, beta list, percentage buckets): [TRAFFIC SEGMENTS]
- Key risk if this goes wrong: [PRIMARY RISK]
- Current monitoring/metrics available: [AVAILABLE METRICS]

Task:
1. Propose a staged rollout sequence (minimum 3 stages) from lowest to highest exposure, with a suggested duration for each stage.
2. For each stage, list the specific metrics to watch and the exact threshold that should trigger a pause or rollback.
3. Define who should approve advancing to the next stage.
4. Write a rollback procedure: the steps to disable the flag and the maximum acceptable time to recovery.
5. Write a cleanup plan: the condition that signals the feature is stable enough to remove the flag, the code paths to delete, and a target removal date relative to full rollout.

Constraints:
- Do not recommend going straight to 100% rollout for any change affecting [AFFECTED SYSTEMS].
- Keep each stage's exit criteria measurable, not subjective.
- Flag any step that depends on information not provided above.

Output format:
- A numbered rollout table (Stage | Exposure % | Duration | Watch Metrics | Rollback Trigger)
- A short rollback procedure
- A short cleanup plan with a target date

Make this prompt yours

Engineering

AI Prompt to Diagnose and Fix Slow Database Queries

This AI prompt helps you diagnose and fix slow database queries by walking through the execution plan, indexing, and query structure instead…

You are a senior database engineer specializing in query performance tuning.

Context:
- Database engine and version: [e.g., PostgreSQL 15, MySQL 8]
- The slow query: [PASTE THE SQL QUERY]
- Execution plan output: [PASTE EXPLAIN / EXPLAIN ANALYZE OUTPUT]
- Relevant table schemas, including existing indexes: [PASTE SCHEMA]
- Approximate row counts for each table involved: [ROW COUNTS]
- How slow it currently runs vs. your target: [CURRENT TIME] vs [TARGET TIME]

Instructions:
1. Identify the most likely cause(s) of the slowness from the execution plan, ranked by probable impact.
2. For each cause, explain in plain language what's happening (for example, "full table scan because no index covers this WHERE clause").
3. Propose the smallest change that would fix the top cause first, before any structural changes.
4. Provide the rewritten query or the exact index definition (CREATE INDEX statement) to test.
5. Note any trade-off the fix introduces, such as added write overhead from a new index.

Constraints:
- Do not suggest denormalizing the schema unless indexing and query rewrites are insufficient.
- Keep the explanation grounded in the specific execution plan provided, not generic query-optimization advice.

Output format:
Return the answer as: Likely Causes (ranked), Recommended Fix, SQL/Index to Test, Trade-offs.

Make this prompt yours

Engineering

AI Prompt to Design a Caching Strategy for a High-Traffic API Endpoint

This prompt asks ChatGPT, Claude, or Gemini to design a caching strategy for a high traffic API endpoint , covering where to cache (client,…

ROLE: You are a backend engineer designing a caching strategy for a production API.

CONTEXT:
- Endpoint: [DESCRIBE THE ENDPOINT, e.g. "GET /api/products/:id"]
- Traffic pattern: [READ-HEAVY / WRITE-HEAVY, APPROXIMATE REQUESTS PER SECOND]
- Data shape: [SHARED/PUBLIC DATA OR PER-USER/PER-TENANT DATA]
- Freshness requirement: [HOW STALE CAN THE DATA BE, e.g. "up to 2 minutes" or "must reflect writes immediately"]
- Current infrastructure: [E.G. "Redis available", "CDN in front of API", "no caching layer yet"]

TASK:
1. Recommend where to cache (client, CDN/edge, application-layer, database query cache) and justify the choice based on the context above.
2. Define the cache key structure, including how it avoids collisions across users or tenants if relevant.
3. Specify the TTL and, separately, the invalidation triggers (e.g. invalidate on write, pub/sub cache bust).
4. Call out at least two failure modes specific to this design (e.g. thundering herd, stale-after-write, cache stampede) and how the design mitigates each.
5. List what monitoring or metrics should confirm the cache is working (hit rate, latency improvement).

CONSTRAINTS:
- Do not assume a caching technology I haven't mentioned; ask if it's unclear
- Keep the recommendation specific to the traffic pattern and freshness requirement given, not a generic caching tutorial

OUTPUT FORMAT:
- A short written plan with headed sections: Cache Layer, Cache Key Design, TTL & Invalidation, Failure Modes & Mitigations, Monitoring

REQUEST:
[DESCRIBE YOUR SPECIFIC ENDPOINT AND SITUATION HERE]

Make this prompt yours