MyInternships.in

Express.js & REST APIs

Node.js Request Validation

Validation checks incoming data before it reaches your business logic. A schema library such as Zod or Joi defines the expected shape once and rejects anything else with a clear error.


What is Request Validation in Node.js?

Validation checks incoming data before it reaches your business logic. A schema library such as Zod or Joi defines the expected shape once and rejects anything else with a clear error.

Why Request Validation matters

Every field a client sends is untrusted. Validating at the boundary prevents malformed data reaching the database and turns vague 500s into precise 400s.

Request Validation example

Schema validation as middleware
JavaScript
import { z } from 'zod';

const createJobSchema = z.object({
  title:   z.string().min(3).max(120),
  company: z.string().min(2),
  stipend: z.number().int().nonnegative().optional(),
  email:   z.string().email(),
  city:    z.enum(['Pune', 'Mumbai', 'Bengaluru', 'Remote']),
});

const validate = schema => (req, res, next) => {
  const result = schema.safeParse(req.body);
  if (!result.success) {
    return res.status(400).json({
      error: 'Validation failed',
      details: result.error.issues.map(i => ({ field: i.path.join('.'), message: i.message })),
    });
  }
  req.body = result.data;   // parsed and coerced
  next();
};

app.post('/api/jobs', validate(createJobSchema), createJob);

Key points to remember

  • Validate body, params and query — all three are user input.
  • Assign the parsed result back so handlers get typed, cleaned data.
  • Zod schemas double as TypeScript types via z.infer.
  • Never rely on client-side validation alone.

Common mistakes with Request Validation

  • Trusting a field because the front-end form validates it.
  • Returning a single vague error instead of listing which fields failed.

Node.js Request Validation— Interview Questions & FAQs

Zod or Joi for Node validation?+

Zod if you use TypeScript — schemas infer types automatically, so there is one source of truth. Joi is mature and fine for plain JavaScript projects.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships