🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

React Authentication: Guards, Tokens and OAuth

React SecurityđŸŸĸ Free Lesson

Authentication in a React app is a state machine wearing a security costume. The state machine part decides, at every moment, whether the app knows who the user is, whether it is still finding out, or whether it has given up and should show a login screen. Get that machine right and the security work becomes straightforward: one source of truth for the session, one guard in front of protected routes, and one place where credentials are exchanged. Get it wrong and you inherit a class of bugs where protected content flashes before logout, users bounce to a login screen mid-session, and the token that everyone assumed was safe sits in a place any script can read.

🔒Where to store the credential

Prefer a cookie set with HttpOnly, Secure and SameSite attributes, so the browser sends it automatically and JavaScript cannot read it. localStorage is readable by any script running on the page, which means one cross-site scripting hole becomes a stolen session.

Decide where the session lives before writing code

Three storage choices are on the table, and each one changes what you can build. A cookie is invisible to JavaScript, travels with every request, and dies when the browser closes or the attribute says so, which makes it the right default for a session token. localStorage persists until you remove it, survives reloads, and is trivially readable by injected script, which makes it acceptable only for non-sensitive UI preferences. An in-memory variable is the safest of all because it disappears on refresh, and it works well as the hot copy of a session that is re-established from a cookie on every load.

The second decision is who validates the credential. If the server validates a signed token on every request, you can revoke nothing until the token expires. If you keep a server-side session record, you can invalidate a single device instantly, at the cost of a lookup per request. Most products keep a short-lived access token with a rotating refresh token bound to a server session record, which gives both fast validation and a real logout button.

The provider: loading, user and the failure case

The single most important property of an auth provider is that it never resolves to a silent default. There are exactly three states: restoring a session, authenticated with a user object, and anonymous. Code that assumes two states ends up rendering protected markup during the brief window before restoration completes, which is how private data flashes on a shared screen.

import { createContext, useContext, useEffect, useMemo, useState } from 'react';

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [status, setStatus] = useState('restoring');
  const [user, setUser] = useState(null);

  useEffect(() => {
    let cancelled = false;

    async function restore() {
      try {
        const res = await fetch('/api/session', { credentials: 'include' });
        if (!res.ok) throw new Error('no session');
        const data = await res.json();
        if (!cancelled) {
          setUser(data.user);
          setStatus('authenticated');
        }
      } catch {
        if (!cancelled) {
          setUser(null);
          setStatus('anonymous');
        }
      }
    }

    restore();
    return () => { cancelled = true; };
  }, []);

  const value = useMemo(() => ({
    status,
    user,
    async signIn(email, password) {
      const res = await fetch('/api/login', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });
      if (!res.ok) throw new Error('Invalid email or password');
      const data = await res.json();
      setUser(data.user);
      setStatus('authenticated');
    },
    async signOut() {
      await fetch('/api/logout', { method: 'POST', credentials: 'include' });
      setUser(null);
      setStatus('anonymous');
    },
  }), [status, user]);

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

export function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error('useAuth must be used inside AuthProvider');
  return ctx;
}

Notice that signOut always reports success to the local state even if the network call fails. A user who clicks logout expects to be logged out; if the request to invalidate the session fails, the client should still clear its own state and let the server expire the record on its own schedule. Confirming a logout by showing the login screen is the correct user-facing outcome.

Guarding routes without flashing protected content

A guard has three jobs: wait while the session is being restored, redirect anonymous visitors while remembering where they were going, and render children only once the answer is known. The redirect target matters more than it looks, because bouncing a deep link to a generic dashboard after login is one of the most common complaints about authentication flows.

import { Navigate, useLocation } from 'react-router-dom';
import { useAuth } from './auth';

export function RequireAuth({ children }) {
  const { status } = useAuth();
  const location = useLocation();

  if (status === 'restoring') {
    return (
      <div className="route-skeleton" role="status" aria-live="polite">
        Checking your session...
      </div>
    );
  }

  if (status === 'anonymous') {
    return (
      <Navigate
        to="/login"
        replace
        state={{ from: location.pathname + location.search }}
      />
    );
  }

  return children;
}

export function LoginPage() {
  const { signIn } = useAuth();
  const location = useLocation();
  const navigate = useNavigate();
  const [error, setError] = useState(null);

  async function onSubmit(e) {
    e.preventDefault();
    setError(null);
    try {
      await signIn(e.target.email.value, e.target.password.value);
      navigate(location.state?.from || '/dashboard', { replace: true });
    } catch (err) {
      setError(err.message);
    }
  }

  return (
    <form onSubmit={onSubmit}>
      <label htmlFor="email">Email</label>
      <input id="email" name="email" type="email" autoComplete="email" required />
      <label htmlFor="password">Password</label>
      <input id="password" name="password" type="password" autoComplete="current-password" required />
      {error && <p role="alert">{error}</p>}
      <button type="submit">Sign in</button>
    </form>
  );
}

Two details separate a decent guard from a good one. The skeleton branch is not optional: without it the guard would see anonymous during restoration and redirect a legitimate user to the login page on every hard refresh. And using replace on the redirect means the back button returns the user to the previous page rather than replaying a redirect loop.

Cookies versus tokens: the actual trade

The comparison is rarely about the string format and almost always about what can read the credential and who is responsible for revoking it.

ConcernHttpOnly cookieToken in localStorageToken in memory
Readable by injected scriptNoYesYes, until reload
Sent automatically with requestsYes, with credentials optionNo, must attach a headerNo, must attach a header
Survives a page refreshYesYesNo
Cross-site request protectionSameSite attributeManual CSRF handlingManual CSRF handling
RevocationServer session recordOnly at expiryOnly at expiry
Works with cross-origin APIsNeeds CORS with credentialsStraightforwardStraightforward

If your API is same-origin, the cookie column wins on every row that matters. If you are calling a third-party API from the browser, you have no choice but to hold a token, and then your job is to keep its lifetime short and its blast radius small.

Refreshing without a logout flash

Refresh is where sessions go to die. The naive approach waits for a request to fail with a 401, refreshes, and retries, which means the first action after an idle period always errors. Better approaches refresh proactively: run the refresh a minute before expiry, or refresh on visibility change when the tab regains focus, and queue concurrent requests so fifteen parallel calls trigger exactly one refresh rather than fifteen.

The queue matters because of a race that is easy to reproduce and hard to spot in testing: two requests both see an expired token, both refresh, and the second rotation invalidates the first refresh token, logging the user out while they are mid-click. Serializing refresh behind a single in-flight promise removes the race entirely.

OAuth without handing your users a password

Third-party sign-in changes the flow rather than the guard. The browser is redirected to the provider, comes back with a short-lived authorization code, and your server exchanges that code for an identity plus a token. The React side only ever sees the resulting session, established the same way as a password login, which means the guard, the provider and the redirect target above are unchanged.

Choose the identity provider by what it gives you: email verification you do not have to build, multi-factor authentication for free, and an account recovery path that is somebody else's on-call problem. Add your own password flow only when a customer contract requires it, and even then prefer to offer it alongside the provider rather than instead of it.

Common Mistakes

Storing the session token in localStorage because it is simpler to attach to requests

Fix: Use an HttpOnly cookie with Secure and SameSite, and attach credentials explicitly when calling your API.

Treating a session that has not finished restoring as anonymous

Fix: Model restoring as a third state and render a skeleton until the check resolves, so refresh never flashes a redirect.

Allowing every request to refresh the token independently

Fix: Serialize refresh behind one in-flight promise so concurrent failures cannot rotate each other's refresh token out.

Redirecting to a fixed dashboard after login

Fix: Carry the intended path in location state and return the user to the deep link they originally requested.

Best Practices

  • Keep one auth context as the only place that knows whether a user exists, and read it through a hook that fails loudly outside the provider
  • Set a short access token lifetime and rotate the refresh token on every use, bound to a server session record you can revoke
  • Treat logout as a client-side certainty: clear local state first, invalidate server-side best effort afterwards
  • Audit protected content by loading a deep link in a private window and confirming nothing renders before authentication resolves

Key Takeaways

  • Model authentication as three states so protected content never renders while a session is still being restored
  • HttpOnly cookies keep the credential out of script reach and travel with requests, which is why they beat localStorage by default
  • Guards must wait, remember the destination, and only then render or redirect, or users lose deep links on every refresh
  • Refresh must be serialized and ideally proactive, because parallel refreshes race and can log a user out mid-action
  • OAuth only changes how the session is established; the provider, guard and redirect logic stay exactly the same
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement