Thuta Learning
Node.js
ProjectsWeb DevelopmentBeginner

POST New Item

Node.jsLesson 2535 min

What you'll walk away with

  • Explain when express.json() fills req.body, and why it can be undefined in Express 5
  • Check each body field for type, length and allowed values, and report every error at once
  • Assign ids with a nextId counter and avoid the users.length + 1 trap
  • Answer with 201 Created and a Location header, and turn malformed JSON into a JSON 400

Explain it simply

Explain it simply

GET asks for data; POST hands new data to the server. When you submit a sign-up form, the browser calls POST /api/users and puts JSON such as { "name": "Hla Hla" } in the request body.

The server acts like a clerk checking forms. Is the form complete, and is what was written valid? If not, it hands back a list of which fields are wrong. If it is, it assigns a new file number (the id), stores the form and replies: created, and here is where you can find it.

Problem → Why → Solution

The problem: trusting the body and counting for ids

The draft below works on the happy path. But when a request arrives without a Content-Type header, req.body is undefined in Express 5, so req.body.name throws a TypeError and the client gets a 500. Sending { "name": 42 } crashes name.trim().

The ids are the worst part. After user 2 is deleted, users.length + 1 is 3, and user 3 already exists, so two users now share an id. On top of that, the draft pushes the whole req.body unchecked, so a client can add { "role": "admin" } and promote itself.

post-draft.js
app.post('/api/users', (req, res) => {
  const name = req.body.name.trim();          // crashes: no body, or name is 42
  const newUser = { ...req.body, id: users.length + 1, name }; // copies any field
  users.push(newUser);
  res.json(newUser);                           // 200, not 201
});

Why this is dangerous

A request body is data that anyone on the internet can send. Even if the frontend form marks name as required, curl or Postman can skip the form and post directly. So the server must check every field itself and pick out only the fields it intends to accept.

Core concept: parse, validate, create, 201

A request to a POST route passes through four stages. Middleware handles the first; your handler does the rest.

1. express.json() parses the body

For a request with Content-Type: application/json, it runs JSON.parse on the body text and stores the result in req.body. If the header does not match, req.body stays undefined in Express 5 (Express 4 used {}), so write req.body ?? {}. If the JSON is malformed, the middleware passes a 400 error with type 'entity.parse.failed' to the error handler.

2. Validate every field and collect errors

Check the type (typeof name === 'string'), the length and the allowed values (ROLES). Do not stop at the first problem: collect every error in an array and return them together, so the user can fix the whole form in one go.

3. Build the new object yourself

Never push req.body directly; take only the validated name and role. The server assigns the id with nextId++. The counter never goes backwards, so ids stay unique even after deletions.

4. Answer 201 with a Location

201 Created means a new resource now exists. The Location header gives its URL (/api/users/4), and the body returns the full user including its id, so the client does not need a follow-up GET.

SituationStatusBody
Valid body201 + Location{ data: user }
Field wrong or missing400{ error, details: [...] }
Malformed JSON400{ error }

400 or 422?

Some APIs answer well-formed JSON with invalid values using 422 Unprocessable Content, and keep 400 for JSON that is broken. The HTTP standard defines both, so either choice is valid. What matters is choosing one and using it on every endpoint. To keep things simple, this course answers all validation errors with 400.

Mental model: the form-checking desk
  1. express.json() turns body into object
  2. Check every field, collect errors
  3. Build a new object from checked fields
  4. Reply 201 + Location + { data }

Never store the object the client sent. Store only an object you built yourself from fields you chose.

General pattern

javascript
app.use(express.json());

app.post('/api/items', (req, res) => {
  const { errors, value } = validate(req.body ?? {});
  if (errors.length) return res.status(400).json({ error: 'msg', details: errors });

  const item = { id: nextId++, ...value };
  items.push(item);
  res.status(201).location(`/api/items/${item.id}`).json({ data: item });
});

The validate function returns a list of errors plus the cleaned value; the handler builds the item from that value only.

POST /api/users with validation

Continuing from the same three users, this adds the POST route. name is trimmed and must be 2 to 50 characters; role defaults to member when omitted. The test sends four requests: a valid one, one with two bad fields, one with no body and one with broken JSON.

app.js
const express = require('express');

const app = express();
app.use(express.json());

const users = [
  { id: 1, name: 'Aung Aung', role: 'admin' },
  { id: 2, name: 'Mya Mya', role: 'member' },
  { id: 3, name: 'Zaw Zaw', role: 'member' },
];
let nextId = 4; // never reused, even after a delete
const ROLES = ['admin', 'member'];

function validateUser(body) {
  const errors = [];
  const name = typeof body.name === 'string' ? body.name.trim() : '';
  if (name.length < 2 || name.length > 50) errors.push('name must be 2-50 characters');
  const role = body.role ?? 'member';
  if (!ROLES.includes(role)) errors.push(`role must be one of: ${ROLES.join(', ')}`);
  return { errors, value: { name, role } };
}

app.post('/api/users', (req, res) => {
  const { errors, value } = validateUser(req.body ?? {});
  if (errors.length > 0) {
    return res.status(400).json({ error: 'Validation failed', details: errors });
  }
  const user = { id: nextId++, ...value };
  users.push(user);
  res.status(201).location(`/api/users/${user.id}`).json({ data: user });
});

// Error handler: malformed JSON from express.json() arrives here
app.use((err, req, res, next) => {
  if (err.type === 'entity.parse.failed') {
    return res.status(400).json({ error: 'Body is not valid JSON' });
  }
  res.status(500).json({ error: 'Internal server error' });
});

const server = app.listen(0, async () => {
  const url = `http://localhost:${server.address().port}/api/users`;
  const json = { 'Content-Type': 'application/json' };
  const attempts = [
    ['valid', { headers: json, body: JSON.stringify({ name: '  Hla Hla  ' }) }],
    ['invalid', { headers: json, body: JSON.stringify({ name: 'K', role: 'owner' }) }],
    ['no body', {}],
    ['broken JSON', { headers: json, body: '{"name": "Ko' }],
  ];
  for (const [label, init] of attempts) {
    const res = await fetch(url, { method: 'POST', ...init });
    const where = res.headers.get('location') ?? '-';
    console.log(`${label}: ${res.status} location=${where}`);
    console.log(`  ${JSON.stringify(await res.json())}`);
  }
  console.log('users in memory:', users.length);
  server.close();
});

Code breakdown

  1. Safe bodyconst { errors, value } = validateUser(req.body ?? {});

    Without a body req.body is undefined, so ?? {} substitutes an empty object. That is why the "no body" request gets a 400 instead of a crash.

  2. Type before trimconst name = typeof body.name === 'string' ? body.name.trim() : '';

    trim() is only called on a string. " Hla Hla " becomes "Hla Hla", while a number such as 42 becomes '' and fails the length check.

  3. Unique idsconst user = { id: nextId++, ...value };

    The server assigns the id, and value contains only name and role, so a client cannot sneak in its own id or extra fields.

  4. 201 and Locationres.status(201).location(`/api/users/${user.id}`).json({ data: user });

    These methods chain. The output shows location=/api/users/4.

  5. JSON parse errorsif (err.type === 'entity.parse.failed') {

    A middleware with four parameters is an error handler. Without it, Express would answer the broken-JSON request with an HTML error page.

You should see
valid: 201 location=/api/users/4
  {"data":{"id":4,"name":"Hla Hla","role":"member"}}
invalid: 400 location=-
  {"error":"Validation failed","details":["name must be 2-50 characters","role must be one of: admin, member"]}
no body: 400 location=-
  {"error":"Validation failed","details":["name must be 2-50 characters"]}
broken JSON: 400 location=-
  {"error":"Body is not valid JSON"}
users in memory: 4

When a POST is sent twice: idempotency

Users double-click "Sign up", and client libraries retry on slow networks. POST is not idempotent, so if both requests arrive you get two users. There are two common fixes. One is to check a field that must be unique, such as email, and answer 409 Conflict if it already exists. The other is for the client to send a random Idempotency-Key header with each request, and for the server to answer a repeated key with the response from the first attempt. Payment APIs commonly use the second approach.

In real projects

In real projects

Real projects rarely hand-write a function like validateUser(); they use a schema library such as zod. A schema declares types, lengths and defaults in one place and produces the error list automatically. The principle is the same as in this lesson: use only validated values.

With a database, the database assigns ids itself (auto-increment or UUID), and fields like email get a unique constraint. When two requests arrive at the same moment, a check in JavaScript is not enough; only the database constraint gives the final guarantee. On the frontend, the details array from a 400 response is shown in red under each form field. Frontend checks still help, but only for speed and comfort; the server check is the one that protects your data.

Common mistakes

Common mistakes

Registering express.json() after the route

Middleware runs in the order it is registered. Put app.use(express.json()) after app.post() and the body has not been parsed when the route runs. req.body is undefined, and it looks as if the client never sent a name.

Using users.length + 1 as the id

After a single delete the length drops and an existing id is handed out again. GET /api/users/3 then finds only the first of the two users, and the second becomes unreachable. Use a counter that never goes backwards.

Answering creation with 200

200 only says the request worked; 201 says precisely that a new resource exists. API tests and client code often check for 201, so this small difference breaks the contract.

Best practices

Best practices

  • Keep validation out of the handler in a function that returns { errors, value }; a PATCH route can reuse it
  • Name the field and the rule in each error message ("name must be 2-50 characters")
  • Limit the request body size; express.json() defaults to 100kb
  • Do not let clients set security-sensitive fields like role freely; give admins a separate route for that

Mini challenge

Write a POST route for products

Write POST /api/products for a products resource shaped { id, name, price }. Reject non-JSON bodies with 415, validate name and price, and answer 201 with a Location on success.

  • Answer 415 Unsupported Media Type unless req.is('application/json')
  • name must be a string that is not just spaces
  • price must be a finite number above 0 (the string "1800" is rejected)
  • Assign the id with a nextId counter and answer 201 with Location and { data }
products.js
const express = require('express');
const app = express();
app.use(express.json());

const products = [{ id: 1, name: 'Green tea', price: 2500 }];
let nextId = 2;

app.post('/api/products', (req, res) => {
  // TODO: 415 unless the request is application/json
  // TODO: collect details for a bad name and a bad price; 400 if any
  // TODO: build { id, name, price }, push it, answer 201 + Location
});

// TODO: listen on 0, POST a valid product, a string price and a form body,
//       print status, Location and body, then close the server

Expected: Mohinga gets 201 with /api/products/2, the string price gets 400, the form body gets 415, and the last line reads products: Green tea, Mohinga.

Show hint

typeof '1800' is 'string', so a typeof price !== 'number' check catches string prices. Number.isFinite() also rejects NaN and Infinity.

Show solution
products.js
const express = require('express');

const app = express();
app.use(express.json());

const products = [{ id: 1, name: 'Green tea', price: 2500 }];
let nextId = 2;

app.post('/api/products', (req, res) => {
  if (!req.is('application/json')) {
    return res.status(415).json({ error: 'Send the body as application/json' });
  }

  const { name, price } = req.body;
  const details = [];
  if (typeof name !== 'string' || name.trim() === '') {
    details.push('name is required');
  }
  if (typeof price !== 'number' || !Number.isFinite(price) || price <= 0) {
    details.push('price must be a positive number');
  }
  if (details.length > 0) {
    return res.status(400).json({ error: 'Validation failed', details });
  }

  const product = { id: nextId++, name: name.trim(), price };
  products.push(product);
  res.status(201).location(`/api/products/${product.id}`).json({ data: product });
});

const server = app.listen(0, async () => {
  const url = `http://localhost:${server.address().port}/api/products`;
  const asJson = (body) => ({
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  const tries = [
    asJson({ name: 'Mohinga', price: 3000 }),
    asJson({ name: 'Tea leaf salad', price: '1800' }),
    { method: 'POST', body: 'name=Coffee&price=1500' },
  ];
  for (const init of tries) {
    const res = await fetch(url, init);
    const location = res.headers.get('location') ?? '';
    console.log(res.status, location, JSON.stringify(await res.json()));
  }
  console.log('products:', products.map((p) => p.name).join(', '));
  server.close();
});

Quick quiz 1 / 3

In an Express 5 app, a POST arrives with no Content-Type header. What is req.body after express.json()?

Quick quiz 2 / 3

Users 1, 2 and 3 exist and user 2 is deleted. A new user is created with id: users.length + 1. What is its id?

Quick quiz 3 / 3

The example app receives a POST with { "name": "Ko", "role": "admin", "id": 1 }. What id does the created user get?

What to remember

  • Register express.json() above the routes and guard against an undefined req.body with ?? {}
  • Check each field for type, length and allowed values; return every error in a details array with 400
  • Build a new object from validated fields instead of storing the client's object, and assign ids with a nextId counter
  • On success send 201 Created, a Location header and { data }; turn malformed JSON into a JSON 400 with an error handler

Express routing — Express.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

POST New Item | Thuta Learning