Skip to content

Interview PrepREST API design · Core

Validating Input ​

64. Why should API input be validated and sanitized? ​

The short answer

Because everything a client sends is under the client's control, including anything an attacker chooses to send, and TypeScript types do not exist at runtime. Without validation, wrong types, missing fields, huge values and malicious strings reach your business logic and database, causing crashes, corrupted data, security holes such as injection and mass assignment, and confusing errors. Validating at the boundary means the rest of the code can trust its inputs, and clients get clear, early error messages.

What unvalidated input breaks:

ts
app.post('/orders', async (req, res) => {
  const { items, couponCode } = req.body                    // no checks at all
  const total = items.reduce((s, i) => s + i.price * i.qty, 0)
  await db.orders.insert({ ...req.body, total })            // whatever the client sent
})
Attack or accidentEffect
items missingTypeError, a 500 instead of a clear 400
qty: -5A negative total, money refunded to the attacker
price: 0.01 sent by the clientThe client sets its own prices
"role": "admin" in the body, spread into the insertMass assignment: the attacker promotes themselves
A 10 MB stringMemory and database bloat
couponCode: { "$ne": null }NoSQL injection in some databases

The fixed version takes only known fields, checks each one, and reads prices from the database, never from the client:

ts
const CreateOrder = z.object({
  items: z.array(z.object({ sku: z.string().max(64), qty: z.number().int().min(1).max(20) })).min(1).max(50),
  couponCode: z.string().max(32).optional(),
}).strict()                                                   // unknown fields are rejected

app.post('/orders', async (req, res) => {
  const input = CreateOrder.parse(req.body)                   // a ZodError becomes a 400 in the error handler
  const order = await orders.create(req.user!.id, input)      // prices looked up server-side
  res.status(201).json(order)
})

65. What is the difference between validation and sanitization? ​

The short answer

Validation checks whether input is acceptable and rejects it if not: is this a valid email, a positive whole number, one of the allowed statuses? Sanitisation changes input into a safer or more normal form: trimming spaces, lower-casing an email, removing dangerous HTML from a comment. Validate first and reject what is wrong; sanitise only where a transformation is genuinely meant. Remember that protection against injection and XSS mostly comes from encoding output for its context and parameterised queries, not from scrubbing input.

ValidationSanitisation
QuestionIs this acceptable?How do I make it clean or normal?
On bad inputReject with 400Change it and continue
Examplesqty is an integer from 1 to 20; email formatTrim, lower-case, collapse spaces, strip HTML tags
Risk if overusedNoneSilently changing data the user meant

Where sanitising is right:

ts
const SignUp = z.object({
  email: z.string().trim().toLowerCase().email(),        // normalise, then validate
  displayName: z.string().trim().min(1).max(50),
})

Where it is the wrong tool: "sanitising" a search box by removing quotes to prevent SQL injection. That breaks legitimate searches for names like O'Brien and still leaves gaps. The real protection is a parameterised query. Likewise, the defence against XSS is escaping output when you render it, which React does by default (the XSS question). Sanitising HTML is needed only when you deliberately accept and display rich text.

66. How would you validate request data using express-validator? ​

The short answer

express-validator provides chains of checks you place as middleware on a route, such as body('email').isEmail() or param('id').isUUID(), built on the validator.js library. After the chains, a small middleware calls validationResult(req) and responds with 400 and the list of problems if there are any. matchedData(req) then gives only the fields that were validated, which protects against extra fields. It suits teams that prefer validation declared next to the route.

ts
import { body, param, query, validationResult, matchedData } from 'express-validator'

const validate = (req: Request, res: Response, next: NextFunction) => {
  const result = validationResult(req)                                              // (1)
  if (!result.isEmpty()) return res.status(400).json({ type: 'validation_error', errors: result.array() })
  next()
}

app.post(
  '/customers/:id/addresses',
  param('id').isString().matches(/^cus_[a-z0-9]{12}$/),                            // (2)
  body('line1').trim().notEmpty().isLength({ max: 100 }),
  body('postcode').trim().toUpperCase().isPostalCode('GB'),                         // (3)
  body('isDefault').optional().isBoolean().toBoolean(),
  validate,
  async (req, res) => {
    const data = matchedData(req)                                                   // (4)
    res.status(201).json(await addresses.add(data.id, data))
  },
)
  1. Collect every failed check from the chains above.
  2. Validate path parameters too, not only the body.
  3. Sanitisers and validators in one chain: trim and upper-case, then check the UK postcode format.
  4. Only validated fields: anything extra the client sent is left out.

Trade-off: chains on each route are readable for small APIs, but the rules are not reusable as types. Schema libraries such as Zod define a shape once and derive the TypeScript type from it (question 67).

67. How do Joi and Zod help validate API input? ​

The short answer

Both let you describe the expected shape of data as a schema, with types, required fields, ranges, formats and nested objects, then check any value against it and get either clean, converted data or a detailed list of errors. Joi is the older, mature library from the hapi ecosystem, with rich rules. Zod is TypeScript-first: the same schema gives you the TypeScript type with z.infer, so validation and types cannot drift apart, which is why it has become the common choice in TypeScript projects.

Zod:

ts
import { z } from 'zod'

export const CreateProduct = z.object({
  sku: z.string().regex(/^[a-z0-9-]{3,40}$/),
  name: z.string().trim().min(2).max(120),
  pricePence: z.number().int().positive(),
  tags: z.array(z.string().max(20)).max(10).default([]),
})
export type CreateProduct = z.infer<typeof CreateProduct>                 // (1)

export const validateBody = (schema: z.ZodType) => (req: Request, res: Response, next: NextFunction) => {
  const result = schema.safeParse(req.body)
  if (!result.success) return res.status(400).json({ type: 'validation_error', issues: result.error.issues })
  req.body = result.data                                                  // (2)
  next()
}

app.post('/products', requireRole('admin'), validateBody(CreateProduct), createProduct)
  1. The TypeScript type comes from the schema: change the schema and the type changes with it.
  2. Replace the body with the parsed result: defaults applied, strings trimmed, unknown fields removed.

Joi, the same rules:

ts
import Joi from 'joi'

const CreateProductJoi = Joi.object({
  sku: Joi.string().pattern(/^[a-z0-9-]{3,40}$/).required(),
  name: Joi.string().trim().min(2).max(120).required(),
  pricePence: Joi.number().integer().positive().required(),
  tags: Joi.array().items(Joi.string().max(20)).max(10).default([]),
})
const { error, value } = CreateProductJoi.validate(req.body, { abortEarly: false, stripUnknown: true })
ZodJoiexpress-validator
TypeScript types from the schemaYesNo, separate typesNo
StyleSchemasSchemasChains per route
Reuse in front end and back endEasyPossibleNo
OpenAPI generationPlugins availablePlugins availableLimited

68. Where should validation occur in a layered backend application? ​

The short answer

At several layers, each with its own job. At the edge, in the HTTP layer, validate the shape: types, required fields, lengths, formats and allowed values, and reject bad requests with 400 before any business code runs. In the service layer, check business rules that need context or data: is the coupon still valid, is the item in stock, may this user do this. In the database, enforce invariants with constraints: unique keys, foreign keys, NOT NULL and checks, as the last line of defence. Client-side checks are only for user experience.

client forminstant feedbacknot trusted① HTTP layershape, types, limits400 if wrong② service layerbusiness rules409, 403, 422③ databaseconstraintslast line of defenceeach layer checks what only it can know; none trusts the one before it blindly
Three walls, each with a different job. ① The HTTP layer rejects malformed input. ② The service enforces rules that need data and context. ③ The database refuses anything that would break its invariants, even if code above has a bug.
LayerChecksExampleResponse
ClientConvenience onlyRequired field highlighted as you typeNone: never trusted
HTTP, edgeShape, types, lengths, formatsqty is an integer from 1 to 20400
Service, domainRules needing data or contextCoupon expired, stock too low, not your order409, 422, 403
DatabaseInvariantsUnique email, order must reference an existing customerMapped to 409

Why the database still matters when code already checks: two requests arriving at the same moment can both pass a "is this email taken?" check in code, and then both insert. A unique constraint in the database is the only thing that reliably stops the second insert (the custom errors question shows mapping that error to 409).

Validate outputs too, where it matters: a response schema that strips unexpected fields stops an internal field, such as a password hash, from leaking if someone adds it to a database query by mistake.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Interview Prep
Express & REST APIs
Express
REST API design
Testing
Other topics
Nothing picked yet