Skip to the workspace
Pebellslearn by building
Auth and the API Contract  ›  Lesson

Guarding Routes and Rows

JWT Auth 14 minThe server protects data with two checks, a route guard that requires a valid login and a row guard that matches the owner taken from the verified token, while the client only hides actions and reacts to 401 by sending the user to log in.

full stack / Guarding Routes and Rows

Explore each scene at your own pace.

01 · The rule

The rule

Guarding Routes and Rows

Logging in tells Sprout who you are. On its own, it does not stop you from reading someone else's plants. Real protection takes two checks on the server, "are you logged in?" and "is this yours?", while the browser's part is only to make the experience smooth.

The rule

The client hides; the server forbids.

Guard the route. Every private route runs requireUser first. No valid token means 401.

app.delete('/api/plants/:id', requireUser, async (req, res) => {
  const { rowCount } = await pool.query(
    'DELETE FROM plants WHERE id = $1 AND owner_id = $2',
    [req.params.id, req.user.id]
  );
  if (rowCount === 0) return res.status(404).json({ error: 'Plant not found' });
  res.sendStatus(204);
});

Guard the row. Every query on owned data also matches the owner, and the owner always comes from req.user.id, which the server read from a verified token. It never comes from the request body, a hidden field or the URL, because the client controls all of those. If nothing matches, answer 404: that way Sprout does not even confirm that someone else's plant 31 exists.

Two different refusals.

  • 401 Unauthorized means "I don't know who you are": no token, a bad one, or an expired one. The client should send the user to log in.
  • 403 Forbidden means "I know who you are, and you may not do this", such as a regular user calling an admin-only route. Logging in again will not help.

The client's part is comfort, not protection. It hides buttons the user cannot use, and it reacts to 401 in one place:

export async function api(path, options = {}) {
  const res = await fetch(path, options);
  if (res.status === 401) {
    window.location.assign('/login');
    throw new Error('Not logged in');
  }
  return res;
}

Every screen calls api(...) instead of fetch(...), so an expired login anywhere in the app leads calmly to the login page.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.