Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 39 ยท Projects and Practice

Practice Exercises

Practice error boundaries, sessions, guards, caching and tests in Remix and React Router with six runnable exercises, each with a starter, checks and a worked solution.

Reading about loaders and sessions is not the same as writing them. These six exercises each take a rule from this part of the course and ask you to implement the logic. The code runs in the editors as plain JavaScript stand-ins, because the live editor cannot run a React Router server. Each starter prints PASS or FAIL per check, so you know when you are done. Try first; the solution follows each exercise in a read-only block, so cover it up until you have a result.

Exercise 1: the nearest boundary

Complete nearestBoundary(routes, failingIndex). routes is an array from the root (index 0) down to the deepest route; each has an id and optionally a boundary string. Return the boundary of the nearest route at or above failingIndex, or 'default 500' if none has one.

Node.js Exercise 1: nearest boundary

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

JavaScript
// solution
function nearestBoundary(routes, failingIndex) {
  for (let i = failingIndex; i >= 0; i--) {
    if (routes[i].boundary) return routes[i].boundary;
  }
  return 'default 500';
}

Exercise 2: safe return path

Write safeReturn(value) that returns value only if it is a local path: a string starting with a single / (not //, not /\). Otherwise return /dashboard. This prevents an open redirect after login.

Node.js Exercise 2: safe return path

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

JavaScript
// solution
function safeReturn(value) {
  return typeof value === 'string' && /^\/(?![/\\])/.test(value) ? value : '/dashboard';
}

Exercise 3: signed values

Implement sign(value, secret) and verify(token, secret) using HMAC-SHA256. A token is base64url(json).base64url(mac). verify returns the value, or null if the token was tampered with or signed with another secret.

Node.js Exercise 3: sign and verify

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

JavaScript
// solution
const mac = (body, secret) => createHmac('sha256', secret).update(body).digest('base64url');

function sign(value, secret) {
  const body = Buffer.from(JSON.stringify(value)).toString('base64url');
  return `${body}.${mac(body, secret)}`;
}

function verify(token, secret) {
  const [body, given] = String(token).split('.');
  if (!body || !given) return null;
  const a = Buffer.from(given), b = Buffer.from(mac(body, secret));
  if (a.length !== b.length || !timingSafeEqual(a, b)) return null;
  return JSON.parse(Buffer.from(body, 'base64url').toString());
}

Exercise 4: ownership and status codes

Write getNote(notes, userId, id). It returns { status: 200, note } for the owner, { status: 404 } when the note does not exist or belongs to someone else, and { status: 302, location: '/login' } when userId is missing.

Node.js Exercise 4: ownership

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

JavaScript
// solution
function getNote(notes, userId, id) {
  if (!userId) return { status: 302, location: '/login' };
  const note = notes.find((n) => n.id === id && n.ownerId === userId);
  return note ? { status: 200, note } : { status: 404 };
}

Exercise 5: choose Cache-Control

Write cachePolicy({ signedIn, isAsset, hashed }) returning the right header: fingerprinted assets public, max-age=31536000, immutable; other assets public, max-age=3600; signed-in documents private, no-store; anonymous documents public, max-age=60, s-maxage=3600, stale-while-revalidate=86400.

Node.js Exercise 5: cache policy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

JavaScript
// solution
function cachePolicy({ signedIn = false, isAsset = false, hashed = false }) {
  if (isAsset) return hashed ? 'public, max-age=31536000, immutable' : 'public, max-age=3600';
  if (signedIn) return 'private, no-store';
  return 'public, max-age=60, s-maxage=3600, stale-while-revalidate=86400';
}

Exercise 6: write a loader test

Complete the two tests for the loader below using node:assert: one for a signed-in owner (expect the note) and one for a visitor with no cookie (expect a rejected response with status 302).

Node.js Exercise 6: test the loader

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

JavaScript
// solution
await test('owner gets the note', async () => {
  const request = new Request('http://x/notes/1', { headers: { Cookie: 'uid=u1' } });
  const result = await loader({ request, params: { id: '1' } });
  assert.equal(result.note.title, 'Hello');
});

await test('visitor is redirected', async () => {
  const request = new Request('http://x/notes/1');
  await assert.rejects(loader({ request, params: { id: '1' } }), { status: 302 });
});

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. In exercise 4, why does another user's note return 404 rather than 403?

    Revealing that a record exists leaks information; treating it as missing is safer.
  2. 2. Why does verify in exercise 3 compare with timingSafeEqual?

    Constant-time comparison avoids timing attacks on secrets and signatures.
  3. 3. Which header suits a hashed JavaScript file?

    A hash in the name means the content never changes, so it can be cached for a year.

Summary

  • Practice the rules, not just the syntax: boundaries bubble up, return paths must be local, cookies need signatures, queries need owners, and cache headers follow privacy.
  • Loaders and actions are plain functions, so they are easy to test with real Request objects.
  • Re-run the starters after changes until every line prints PASS.

Next: Interview Questions