Back to cookbook

AI Prompt to Build a React Authentication Flow With Protected Routes

0 views Published

Make this prompt yours

Share

This AI prompt for a React authentication flow generates the pieces a typical app needs to gate pages behind a login: a login form, an auth context that tracks the current user and token, and a protected-route wrapper that redirects unauthenticated users. It's aimed at frontend developers wiring up auth against an existing backend API who want a consistent starting structure instead of assembling it from scattered tutorial snippets.

The prompt separates concerns the way a real app should: a context provider owns the session state and exposes login/logout functions, while a ProtectedRoute component checks that state and redirects to a login page when there's no valid session, rather than letting protected pages render first and flash their content. It also asks the model to handle the loading state while the session is being verified on page load, which is the detail most quick auth examples skip and that causes a visible flash of protected content before redirect.

Because this kind of prompt produces several interrelated files at once, running the filled-in version through Prompt Optimizer in its Coding mode first can tighten the constraints around state shape and error handling before you spend a generation cycle on it.

Prompt template

Make this prompt yours

prompt-template
296 tokens
ROLE You are a senior React developer building a reusable authentication flow. CONTEXT Framework: [REACT_VERSION, e.g. React 18] Routing library: [ROUTING_LIBRARY_AND_VERSION, e.g. React Router v6] Backend auth endpoints: [LOGIN_ENDPOINT], [LOGOUT_ENDPOINT], [SESSION_CHECK_ENDPOINT] Token storage method: [TOKEN_STORAGE_METHOD, e.g. httpOnly cookie set by the server] Styling approach: [STYLING_APPROACH, e.g. Tailwind CSS] TASK Generate the following, using functional components and hooks: 1. An AuthContext and AuthProvider that exposes the current user, a loading flag, and login/logout functions. 2. A login form component that calls the login function and displays validation and API errors. 3. A ProtectedRoute component that redirects unauthenticated users to [LOGIN_ROUTE_PATH], preserving the originally requested URL for post-login redirect. 4. On initial app load, verify any existing session before rendering protected routes, showing a loading indicator during the check. CONSTRAINTS - Do not render protected page content until the session check has completed. - Handle network and 401 errors from the auth endpoints gracefully, with user-facing messages. - Keep components small and composable; do not put API calls directly inside UI components. OUTPUT FORMAT Provide each file separately with a filename comment at the top, followed by a 2-3 sentence summary of how the pieces connect together.

Want it sharper? Optimize this prompt with Prompt Optimizer, check it with the Prompt Debugger or shorten it with the Token Optimizer.

Example input

example-input
52 tokens
Framework: React 18 Routing library: React Router v6 Backend auth endpoints: POST /api/login, POST /api/logout, GET /api/session Token storage method: httpOnly cookie set by the server Styling approach: Tailwind CSS

When to use it

  • You're starting a new React app that needs login-gated pages and want a clean auth context structure from the start.
  • You're replacing ad-hoc if (user) checks scattered across pages with a single reusable protected-route pattern.
  • You need to handle the brief loading state while a stored token is being verified on app startup.
  • You want a consistent pattern for redirecting unauthenticated users back to login and then on to their original destination after they sign in.

Best practices

  • Specify exactly how the token is stored (memory, httpOnly cookie, or localStorage) since this changes the security model and the code the model should generate.
  • Ask for a loading state in the auth context so protected routes don't render briefly before a redirect fires on page refresh.
  • Request that the protected-route component preserve the originally requested URL so the user lands there after logging in, not just on a generic home page.
  • Specify your routing library version (React Router v6 vs. v7, for example) since the redirect and route-nesting APIs differ between versions.

Common mistakes

  • Not specifying token storage, which often results in plain localStorage being used by default even when that's not appropriate for the app's security needs.
  • Skipping the loading state, causing protected content to flash on screen before the redirect to login happens.
  • Forgetting to ask for logout behavior that clears both the stored token and any cached user data in the context.
  • Not stating the routing library and version, leading to generated code that mixes APIs from different React Router versions.

FAQs

How do I keep a user logged in after a page refresh?

Store the session server-side behind an httpOnly cookie, then call a session-check endpoint on initial app load to restore the user into your auth context before rendering protected routes.

Should I store the auth token in localStorage or a cookie?

An httpOnly cookie set by the server is generally safer since it isn't readable by JavaScript, which reduces exposure to XSS; localStorage is simpler but should be avoided for sensitive tokens if you can use cookies instead.

How do I redirect a user back to the page they wanted after login?

Have the protected route pass the current location in the redirect state when sending the user to the login page, then read that state after a successful login to navigate them to their original destination.

Does this pattern work with Next.js instead of React Router?

The same separation (auth context, loading state, redirect on missing session) applies, but Next.js typically handles the redirect in middleware or a layout component instead of a client-side ProtectedRoute wrapper.

What tool pairs well with this prompt?

Prompt Optimizer — its Coding mode is useful for tightening the constraints around state shape and error handling in a multi-file prompt like this before you spend a generation cycle on it.

Found this prompt useful? Share it.

Share

More in React Prompt Recipes

React Prompt Recipes

AI Prompt to Build a React Billing Dashboard Component Using Stripe's MCP Server

This prompt is for frontend developers who need to build a React billing dashboard component that shows a customer's live subscription, invo…

ROLE:
You are a senior React/TypeScript developer building a billing dashboard component for a SaaS product.

CONTEXT:
The component should display billing data for a customer, retrieved via Stripe's MCP server: [LIST_DATA_NEEDED_E.G._SUBSCRIPTION_PLAN_NEXT_CHARGE_DATE_PAYMENT_METHOD_RECENT_INVOICES]
Framework/styling: [REACT_VERSION_AND_STYLING_APPROACH_E.G._TAILWIND_CSS_MODULES]

CONSTRAINTS:
- Handle these billing states explicitly: [LIST_STATES_E.G._ACTIVE_PAST_DUE_CANCELED_PENDING_NO_PAYMENT_METHOD]
- Show a loading skeleton while data is being fetched, and a clear error state if the fetch fails
- Format currency and dates using the customer's actual locale/currency, not a hardcoded format
- Separate the data-fetching hook from the presentational component

OUTPUT FORMAT:
1. A short explanation of the component's structure (hook + presentational component)
2. The full TypeScript code, in a single fenced code block, with comments marking where each billing state is handled
3. A one-line note on any assumption you made about the data shape returned by the MCP server

Make this prompt yours

React Prompt Recipes

AI Prompt to Build a React Dark Mode Toggle with System Preference Detection

A React dark mode toggle prompt asks ChatGPT, Claude, or Gemini to generate a theme switching component that respects the user's OS level li…

Role: You are a senior React developer building a reusable UI component.

Context:
Framework/setup: [REACT VERSION, e.g. React 18 with Vite, Next.js App Router]
Styling approach: [CSS variables / Tailwind CSS dark class / CSS-in-JS library]
Component location/usage: [where the toggle will live, e.g. app header, settings page]

Task:
Build a dark mode toggle component with this exact behavior:
1. On first load, detect the user's OS preference via the `prefers-color-scheme` media query and use it as the initial theme, applied before the main content paints (no flash of the wrong theme).
2. If the user has previously made an explicit choice, that stored choice overrides the OS preference on future visits.
3. Persist the user's explicit choice in [STORAGE MECHANISM, e.g. localStorage].
4. Listen for theme changes made in other open tabs and update this tab's theme to match.
5. Expose the current theme and a toggle function via [CONTEXT/HOOK NAME, e.g. a useTheme hook] so other components can read and react to it.

Constraints:
- Use [STYLING APPROACH] to apply the theme, not inline style objects
- Include accessible labeling (aria-label or visible text) that reflects the current state
- Keep the component dependency-free unless [ALLOWED LIBRARIES] are specified

Output format:
Return the full component code in a fenced code block, followed by a short usage example showing how to wrap the app and consume the hook elsewhere.

Make this prompt yours

React Prompt Recipes

AI Prompt to Build a React Kanban Board With Drag-and-Drop

This prompt gives ChatGPT, Claude, or Gemini a complete specification for building a React Kanban board with drag and drop column reordering…

You are a senior React developer specializing in accessible, production-ready UI components.

Context:
- Framework: [REACT VERSION, e.g. React 18 with TypeScript]
- Drag-and-drop library: [LIBRARY NAME, e.g. @dnd-kit/core]
- Styling approach: [e.g. Tailwind CSS, CSS Modules, styled-components]
- Columns or workflow stages: [LIST OF COLUMN NAMES, e.g. Backlog, In Progress, Review, Done]
- State source: [e.g. local state, Zustand store, REST API endpoint]

Build a Kanban board component with the following requirements:
1. Render one column per workflow stage listed above, each showing its card count
2. Support dragging cards between columns and reordering cards within a column
3. Support keyboard-based reordering, not mouse-only interaction, for accessibility
4. Identify cards by a stable [ID FIELD NAME] field, never by array index
5. Call a [CALLBACK NAME] function on every successful move, passing the card id, source column, destination column, and new index
6. Show an optimistic UI update immediately, then roll back if [CALLBACK NAME] rejects
7. Handle empty columns and drops outside any valid column gracefully

Output format:
- The main board component
- Column and Card subcomponents
- Any custom hooks used for drag state
- A short usage example showing how to wire [CALLBACK NAME] to a real API call
- Brief notes on any library-specific setup required, such as providers, context, or CSS imports

Make this prompt yours