Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 36 ยท Rendering Modes and Functions

Client-Only Routes and Authentication in Gatsby

Build dynamic app areas inside a static Gatsby site: client-only routes with splat pages, private routes, login state, tokens and where to fetch user data.

A static site cannot know who the visitor is: the HTML is the same for everyone. Yet many sites have an account area, a dashboard or a members-only section. The standard Gatsby answer is to keep the public pages static and turn the private part into a client-only app: a single page whose content is rendered in the browser after login.

Client-only routes

Create one page that catches every URL under a prefix. In the file-system routing API, a file named [...].js is a splat route:

JSX
// src/pages/app/[...].js (real Gatsby, read-only)
import * as React from "react"
import { Router } from "@reach/router"
import Profile from "../../components/profile"
import Billing from "../../components/billing"
import PrivateRoute from "../../components/private-route"

export default function App() {
  return (
    <Router basepath="/app">
      <PrivateRoute path="/profile" component={Profile} />
      <PrivateRoute path="/billing" component={Billing} />
    </Router>
  )
}

All of /app/profile, /app/billing and /app/anything serve the same HTML file; the router inside decides what to show. The alternative is gatsby-plugin-create-client-paths with { prefixes: ["/app/*"] }, which achieves the same from gatsby-config.js. Because the content is decided in the browser, search engines should not index it: add noindex in the page Head and exclude /app/* from the sitemap.

Private routes

JSX
// src/components/private-route.js (real Gatsby, read-only)
import * as React from "react"
import { navigate } from "gatsby"
import { useAuth } from "../auth/auth-context"

export default function PrivateRoute({ component: Component, location, ...rest }) {
  const { user, loading } = useAuth()

  React.useEffect(() => {
    if (!loading && !user && location.pathname !== "/login") {
      navigate("/login", { replace: true })
    }
  }, [loading, user, location.pathname])

  if (loading || !user) return <p>Checking your session...</p>
  return <Component location={location} {...rest} />
}

The loading state matters. On first render no user is known yet (the server HTML has none), so you must wait for the check to finish, otherwise logged-in users flash a login redirect.

Where does login state live?

There are three common choices, each with trade-offs:

  1. Cookie set by your backend (HttpOnly, Secure, SameSite). Safest against theft by scripts: the browser sends it automatically, JavaScript cannot read it. The client asks an endpoint such as /api/me (a Gatsby Function) who it is.
  2. Token in memory (a React state or context) that is refreshed from an httpOnly refresh cookie. Good compromise.
  3. Token in localStorage. Simple, but any script on the page (including a compromised dependency) can steal it. Avoid for long-lived tokens.

Third-party services (Auth0, Firebase Auth, Supabase, Clerk) wrap these flows in SDKs. Gatsby is not opinionated: any client library works as long as it only runs in the browser.

Browser-only code and SSR

During gatsby build, React renders in Node, where window and localStorage do not exist. Code that touches them at module load or during render crashes the build with window is not defined. Put it in useEffect, check typeof window !== "undefined", or render the client app only after mount:

JSX
// real Gatsby, read-only
function useIsClient() {
  const [isClient, setIsClient] = React.useState(false)
  React.useEffect(() => setIsClient(true), [])
  return isClient
}

Fetching user data

Do not rely on GraphQL page queries for user data: they run at build time and are public. Fetch it in the browser with the user's credentials, for example fetch("/api/orders", { credentials: "include" }). Show a loading state, handle 401 by redirecting to login, and never put personal data in page-data.json.

A route and guard stand-in

This stand-in is a small router with splat matching and a guard, written in plain JavaScript.

JS Stand-in: client-side routes with a guard

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

No output.

Next, the loading problem: a session that is checked asynchronously needs three states, not two.

JS Stand-in: loading, anonymous and signed-in states

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

No output.

Security notes

  • Client-side guards only change the UI. Real protection must happen on the server: every API endpoint must verify the session itself.
  • Never ship secrets, admin routes or private data inside the static bundle, because any visitor can read it.
  • Use Secure, HttpOnly and SameSite cookie attributes, and protect state-changing requests against CSRF.
  • Redirect after login to a validated local path only (open redirects are an attack vector).

Common mistakes

  • Rendering the private page content on the server and caching it publicly.
  • Checking localStorage during render.
  • Forgetting noindex for client-only pages.
  • Trusting the route guard as the only protection.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the file name for a splat page that matches every URL under /app?

    [...].js is a splat route, so one page serves all nested paths.
  2. 2. Why does a PrivateRoute need a loading state?

    Without it, signed-in users would be redirected to login before the check finishes.
  3. 3. Which storage is safest against scripts stealing a session?

    JavaScript cannot read HttpOnly cookies.
  4. 4. Does a client-side route guard protect your API data?

    Guards are UI only; users can call the API directly.

Summary

  • Keep public pages static; make the account area a client-only app behind a splat route.
  • Guard routes with an auth context that has loading, anonymous and signed-in states.
  • Prefer HttpOnly cookies; fetch user data in the browser, not in GraphQL queries.
  • Avoid window during render; add noindex; enforce security on the server.

Next: Build caching and incremental builds