Thuta Learning
Node.js
ProjectsWeb DevelopmentBeginner

GET All Items

Node.jsLesson 2330 min

What you'll walk away with

  • Write a collection route with app.get() that answers with a { count, data } envelope
  • Treat req.query values as strings, arrays or undefined, and validate them
  • Filter with filter() so the original array is never modified
  • Tell apart a filter with no matches (200 with empty data) from an invalid filter value (400)

Explain it simply

Explain it simply

GET /api/users asks "show me all the users", and the server sends the whole array back as JSON. Every screen that shows a list, such as a contact list in an app or a table in an admin dashboard, has a route like this behind it.

Think of a query string such as ?role=member as a search filter at the library. It is still the same shelf; you are just adding "only members" or "only names containing aw". When nothing matches, the shelf does not vanish: you simply get an empty list.

Problem → Why → Solution

The problem: trusting the query string

The first draft below has three problems. It sends a bare array, so adding a total later means changing the response shape and breaking every client. It writes users = users.filter(...), so a single call with ?role=admin permanently deletes the members from memory. And it returns 404 for an empty result, so the client cannot tell "this route does not exist" from "nothing matched".

get-all-draft.js
let users = [/* ... */];

app.get('/api/users', (req, res) => {
  if (req.query.role) {
    users = users.filter((u) => u.role === req.query.role); // overwrites the data!
  }
  if (users.length === 0) {
    return res.status(404).json({ error: 'No users' });     // empty is not missing
  }
  res.json(users);                                          // bare array, no room to grow
});

Why it goes wrong

The handler runs once per request, but the users variable exists once per module and every request shares it. Writing one request's result back into that shared data affects every request that follows. The query string is also free text that anyone can type, so it must be checked before use.

Core concept: read, filter, wrap the collection

A collection route has a simple job: read and check the query, filter a copy of the data, then wrap the result in an envelope and send it. Each step has one thing to watch.

1. req.query only holds text

With ?limit=5, req.query.limit is the string "5", not the number 5. Express 5's default query parser turns a repeated key (?role=a&role=b) into an array ['a', 'b'], and a missing key is undefined. Your code has to handle all three.

2. Check closed values against a whitelist

For a filter with a closed set of values, like role, check ROLES.includes(role). An unknown value such as guest gets a 400 that lists the valid choices. An array also fails includes(), so this single check covers that case too.

3. filter() returns a new array

Writing let result = users; and then result = result.filter(...) only reassigns a local variable; the shared users array is untouched. Filters can then be chained one after another.

4. Answer with an envelope

Wrapping the list in an object such as { count, data } lets you add total, limit or offset later without breaking existing clients. A bare array has no room for metadata.

RequestStatusWhy
GET /api/users200The collection exists
?search=kyaw (no match)200, data: []The collection exists; the result is empty
?role=guest400The filter value itself is invalid

Express 4 versus Express 5 query parsing

Express 4's default "extended" parser turned ?filter[role]=admin into the nested object { filter: { role: 'admin' } }. Express 5's default "simple" parser keeps it as one plain key named "filter[role]". If you truly need nested queries you can switch back with app.set('query parser', 'extended'), but flat keys are all the APIs in this course need.

Mental model: sieve a copy, never the source
  1. Read query values and check types
  2. Answer 400 at once if invalid
  3. Chain filters on a copy
  4. Send 200 with { count, data }

Never reassign the shared array inside a handler, or one request's result becomes the next request's data.

General pattern

javascript
app.get('/api/items', (req, res) => {
  const { field } = req.query;                  // string | string[] | undefined
  if (field !== undefined && !ALLOWED.includes(field)) {
    return res.status(400).json({ error: 'message' });
  }
  let result = items;                           // local name, shared data untouched
  if (field) result = result.filter((it) => it.field === field);
  res.json({ count: result.length, data: result });
});

Read the query, check it, filter through a local variable and answer with an envelope. When validation fails, return immediately.

GET /api/users with role and search filters

Using the same three users from lesson 22, this adds GET /api/users. The role filter accepts only admin or member, and the search filter matches names without caring about upper or lower case. Once the server is up, the code sends five requests and prints the status, the count and the names.

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' },
];
const ROLES = ['admin', 'member'];

app.get('/api/users', (req, res) => {
  const { role, search } = req.query; // strings, arrays or undefined

  if (role !== undefined && !ROLES.includes(role)) {
    const allowed = ROLES.join(', ');
    return res.status(400).json({ error: `role must be one of: ${allowed}` });
  }

  let result = users;
  if (role) result = result.filter((u) => u.role === role);
  if (typeof search === 'string') {
    const needle = search.toLowerCase();
    result = result.filter((u) => u.name.toLowerCase().includes(needle));
  }

  res.json({ count: result.length, data: result });
});

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  const first = await fetch(`${base}/api/users`);
  const all = await first.json();
  console.log('GET /api/users ->', first.status, 'keys:', Object.keys(all).join(', '));
  console.log('  data[0]:', JSON.stringify(all.data[0]));

  const queries = ['?role=member', '?search=AW', '?search=kyaw', '?role=guest'];
  for (const q of queries) {
    const res = await fetch(`${base}/api/users${q}`);
    const body = await res.json();
    const detail = res.ok ? body.data.map((u) => u.name).join(', ') : body.error;
    const count = body.count ?? '-';
    console.log(`GET /api/users${q} -> ${res.status} count=${count} | ${detail}`);
  }
  server.close();
});

Code breakdown

  1. Read the queryconst { role, search } = req.query; // strings, arrays or undefined

    Destructures the keys from the query string. A key that is not in the URL is undefined.

  2. Whitelist checkif (role !== undefined && !ROLES.includes(role)) {

    If role is present but not in ROLES, the route answers 400. Both ?role=guest and an array value stop here.

  3. Local resultlet result = users;

    result is a local variable pointing at the shared array. The filter() calls below produce new arrays, so users itself never changes.

  4. Case-insensitive searchresult = result.filter((u) => u.name.toLowerCase().includes(needle));

    Both sides are lowercased before comparing, which is why ?search=AW finds "Zaw Zaw".

  5. The enveloperes.json({ count: result.length, data: result });

    With no matches it still sends 200 with count 0 and data []. See the ?search=kyaw line in the output.

You should see
GET /api/users -> 200 keys: count, data
  data[0]: {"id":1,"name":"Aung Aung","role":"admin"}
GET /api/users?role=member -> 200 count=2 | Mya Mya, Zaw Zaw
GET /api/users?search=AW -> 200 count=1 | Zaw Zaw
GET /api/users?search=kyaw -> 200 count=0 |
GET /api/users?role=guest -> 400 count=- | role must be one of: admin, member

When lists grow: order and pagination

Three users can go out in one response, but a hundred thousand would make the response huge and slow. So APIs accept limit and offset (or page) in the query and send one slice at a time. Cap limit at a maximum such as 50, or someone can bypass pagination with ?limit=1000000.

Paging also needs a stable order. Sort by name, and when two names are equal, sort again by a unique key such as id (a tie-breaker). Without it an item can appear on both page 1 and page 2, or on neither. You will build exactly this in the mini challenge.

In real projects

In real projects

An online shop's product page usually offers filters for category, price range and keywords, and all of them reach the server as a query string such as GET /api/products?category=shoes&maxPrice=50000. Because the filters live in the URL, a user can bookmark or share the page and keep them.

With a real database the filtering moves out of JavaScript and into SQL's WHERE and LIMIT clauses. The rules from this lesson stay the same, though: check the query, use whitelists, answer with an envelope, and return 200 for an empty result. Whitelists also help defend against attacks such as SQL injection. Teams usually list every supported filter in the API documentation, so frontend developers never have to guess a parameter name.

Common mistakes

Common mistakes

Treating a query value as a number

With ?limit=5, req.query.limit + 1 is "51", not 6, because it concatenates strings. Convert with Number() and check with Number.isInteger().

Writing the filter result back into the shared array

Writing users = users.filter(...) inside the handler means the first request's filter shapes every later request. It hides in single-request tests and only shows up when two requests arrive in a row, which makes it hard to find.

Answering 404 for an empty result

The collection exists, so finding nothing is not an error. A 404 makes the client mix up a wrong URL with an empty result, and it shows an error screen instead of "No results".

Best practices

Best practices

  • Use the same filter parameter names on every endpoint (search, limit, offset)
  • Keep the default limit small and enforce a maximum; clients that need more can ask for the next page
  • Name the valid values in the error message so client developers do not have to reopen the docs
  • Always define the sort order instead of relying on insertion order

Mini challenge

Add limit and offset pagination

Add pagination to a GET /api/users with five users. Read limit (default 2, allowed 1-50) and offset (default 0) from the query and answer 400 when either is invalid. Sort by name with id as the tie-breaker.

  • A readInt(value, fallback, min, max) helper returns the number, the fallback, or null
  • The response contains total, count, limit, offset and data
  • Sort a [...users] copy, never the shared array
  • ?limit=0 and ?limit=abc both answer 400
paginate.js
const express = require('express');
const app = express();

const users = [/* TODO: five users with id, name and role */];

function readInt(value, fallback, min, max) {
  // TODO: undefined -> fallback; not an integer or out of range -> null
}

app.get('/api/users', (req, res) => {
  // TODO: read limit (default 2, 1-50) and offset (default 0, >= 0)
  // TODO: 400 if either is null
  // TODO: sort a copy by name, then id; slice one page
  // TODO: res.json({ total, count, limit, offset, data })
});

// TODO: listen on port 0, request a few pages, print them, close the server

Expected: No query shows Aung Aung, Hla Hla; ?limit=2&offset=2 shows Ko Ko, Mya Mya; ?offset=4 shows Zaw Zaw, all with total=5; ?limit=0 and ?limit=abc answer 400.

Show hint

Number('abc') is NaN and Number.isInteger(NaN) is false. slice(offset, offset + limit) never throws past the end of the array; it just returns what is left.

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

const app = express();

const users = [
  { id: 1, name: 'Aung Aung', role: 'admin' },
  { id: 2, name: 'Mya Mya', role: 'member' },
  { id: 3, name: 'Zaw Zaw', role: 'member' },
  { id: 4, name: 'Hla Hla', role: 'member' },
  { id: 5, name: 'Ko Ko', role: 'admin' },
];

// Returns the number, the fallback when missing, or null when invalid
function readInt(value, fallback, min, max) {
  if (value === undefined) return fallback;
  const n = Number(value);
  if (!Number.isInteger(n) || n < min || n > max) return null;
  return n;
}

app.get('/api/users', (req, res) => {
  const limit = readInt(req.query.limit, 2, 1, 50);
  const offset = readInt(req.query.offset, 0, 0, Number.MAX_SAFE_INTEGER);
  if (limit === null || offset === null) {
    return res.status(400).json({ error: 'limit must be 1-50 and offset 0 or more' });
  }

  const sorted = [...users].sort((a, b) => a.name.localeCompare(b.name) || a.id - b.id);
  const page = sorted.slice(offset, offset + limit);
  res.json({ total: users.length, count: page.length, limit, offset, data: page });
});

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}/api/users`;
  for (const q of ['', '?limit=2&offset=2', '?offset=4', '?limit=0', '?limit=abc']) {
    const res = await fetch(base + q);
    const body = await res.json();
    const names = body.data ? body.data.map((u) => u.name).join(', ') : body.error;
    const label = q || '(no query)';
    console.log(`${label} -> ${res.status} total=${body.total ?? '-'} | ${names}`);
  }
  server.close();
});

Quick quiz 1 / 3

In the example app, what does GET /api/users?search=kyaw return?

Quick quiz 2 / 3

The request has ?limit=5. After const end = req.query.limit + 1; what is end?

Quick quiz 3 / 3

What happens when the Express 5 example app receives GET /api/users?role=admin&role=member?

What to remember

  • A collection route answers with a { count, data } envelope so fields can be added later
  • req.query values are strings, arrays or undefined, so check them before use
  • Filter through a local variable and never reassign the shared array
  • No matches means 200 with empty data; an invalid filter value means 400

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.

GET All Items | Thuta Learning