Adding Authentication to React AppsEntry 7 of 11

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">.

Notes

  • The route has no element; it exists only to run the action.
  • Submitting via <Form> (not a link) means it runs as an action, which triggers loader revalidation, so the root loader returns null and the UI switches to logged out.
  • The same action is reused for automatic logout (Entry 9).

What / Why / When

What

Ending the user's session on the client.

Why

Removes the token so protected UI and routes are no longer accessible.

When

User clicks Logout, or the token expires.

Code compare

React
// pages/Logout.tsimport { redirect } from "react-router";import { clearAuthToken } from "../util/auth";​export function action() {  clearAuthToken();  return redirect("/");}
React
// App.tsx (children of root)import { action as logoutAction } from './pages/Logout';​{ path: 'logout', action: logoutAction }

AuthService.logout() (Entry 4) clears storage, resets the signal, cancels the timer, and navigates home. No route needed.

No Angular code for this example.

Quick reference

ReactAngular
{ path: 'logout', action }authService.logout()
<Form action="/logout" method="post">(click)="logout()"