Adding Authentication to React AppsEntry 5 of 11
Attaching the Token to Requests
Requests to protected endpoints include the token in the Authorization header so the backend can verify it.
Notes
- Standard format:
Authorization: Bearer <token>. - The course adds the header manually in each protected request (create, edit, delete event).
- A small
authFetchwrapper avoids repeating it. That's the closest React gets to Angular's interceptor. - The backend rejects requests with a missing or invalid token (usually 401). This is the real protection; client checks only improve UX.
What / Why / When
- What
Sending proof of identity with each request.
- Why
Tokens are stateless; the server needs one on every protected call.
- When
Every request to a protected endpoint.
Code compare
// Course approach: header added in the requestconst token = getAuthToken();const response = await fetch(url, { method, headers: { "Content-Type": "application/json", Authorization: "Bearer " + token, }, body: JSON.stringify(eventData),});// services/http.ts — reusable wrapperimport { getAuthToken } from "../util/auth";export function authFetch(input: RequestInfo, init: RequestInit = {}) { const token = getAuthToken(); const headers = new Headers(init.headers); if (token && token !== "EXPIRED") { headers.set("Authorization", `Bearer ${token}`); } return fetch(input, { ...init, headers });}// services/events.tsexport async function deleteEvent(id: string) { const response = await authFetch(`${API}/events/${id}`, { method: "DELETE" }); if (!response.ok) throw new Error("Could not delete event.");}// interceptors/auth.interceptor.tsimport { HttpInterceptorFn } from "@angular/common/http";import { inject } from "@angular/core";export const authInterceptor: HttpInterceptorFn = (req, next) => { const token = inject(AuthService).token(); if (!token) return next(req); return next(req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }));};// app.config.tsproviders: [ provideRouter(routes, withComponentInputBinding()), provideHttpClient(withInterceptors([authInterceptor])),];Services stay unchanged: every HttpClient call gets the header automatically.
Differences and gotchas
- The interceptor applies to all requests, including third-party APIs. Check
req.urlif the token should only go to your own backend. - React's wrapper is opt-in per call; forgetting it leads to unexpected 401s.
Quick reference
| React | Angular |
|---|---|
Authorization: 'Bearer ' + token per request | HttpInterceptorFn |
authFetch() wrapper | withInterceptors([authInterceptor]) |