Secure API Request Handler
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
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.Example input
Method: POST Path: /api/users Fields: email (valid email), name (2-60 chars), age (optional int 13-120)
Example output
```ts
const schema = z.object({
email: z.string().email(),
name: z.string().min(2).max(60),
age: z.number().int().min(13).max(120).optional(),
});
router.post("/api/users", async (req, res) => {
try {
const parsed = schema.safeParse(req.body);
if (!parsed.success) {
return res.status(400).json({ error: { code: "VALIDATION_ERROR", message: parsed.error.issues[0].message } });
}
// Parameterized insert: values never touch the SQL string.
const user = await db.user.create({ data: parsed.data });
return res.status(201).json(user);
} catch {
return res.status(500).json({ error: { code: "INTERNAL_ERROR", message: "Something went wrong" } });
}
});
```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.