11 entries · 14-question quiz

Adding Authentication to React Apps

React ↔ Angular reference. React examples use React 19 + TypeScript with React Router's Data Router API (v7; in v6 import from react-router-dom). Angular examples use modern Angular (standalone components, signals, inject(), @if/@for). Builds on the React Router chapter's events app.

Test yourself

14 questions

  1. 1
    How Authentication Works

    Authentication proves who a user is so the backend can decide whether to grant access to protected resources.

  2. 2
    Switching Login and Signup with Query Params

    One auth page handles both login and signup, switching modes with a query parameter (/auth?mode=login or /auth?mode=signup).

  3. 3
    Sending Credentials in a Route Action

    The auth route's action reads the mode from the request URL, sends the credentials to /login or /signup, and handles validation errors.

  4. 4
    Storing and Reading the Token

    After a successful login, the token is saved in localStorage so it survives page reloads, and helper functions read it back.

  5. 5
    Attaching the Token to Requests

    Requests to protected endpoints include the token in the Authorization header so the backend can verify it.

  6. 6
    Updating the UI Based on Auth State

    A loader on the root route returns the token, and any component reads it with useRouteLoaderData('root') to show or hide UI.

  7. 7
    Logging Out

    A logout route with only an action clears the token and redirects. The navigation submits to it with <Form action="/logout" method="post">.

  8. 8
    Protecting Routes

    A loader that checks for a token and redirects to the login page if there isn't one. It's React Router's closest equivalent to an Angular route guard.

  9. 9
    Token Expiration and Automatic Logout

    Tokens expire (often after one hour). The app stores the expiration time and logs the user out automatically when it's reached.

  10. 10
    Security Notes and Project Structure

    Practical security limits of client-side auth, and where the auth pieces live.

  11. 11
    Summary