Imagine your E-Commerce platform uses a Next.js/WordPress monolith that seamlessly routes users to two React SPAs (seller and customer) via JWTs and OAuth 2.0. To harden this flow against XSS and CSRF, we have to shift all tokens into HTTP-only cookies, implement rotating refresh tokens, and provide a robust logout/expiry strategy. You’ll have a single, secure session across all three applications by the end.

Token Flow Overview

  1. Browser → /api/login: credentials submitted
  2. /api/login → Browser: sets access_token & refresh_token cookies
  3. Browser → /api/graphql: requests include cookies
  4. /api/graphql → Browser: returns user context
  5. Role-Based Redirects: Next.js sends user to Seller or Customer SPA

Prerequisites

  • Node.js ≥14
  • A Next.js project with WordPress authentication (OAuth 2.0)
  • React SPAs for Seller and Customer, served under the same domain
  • A token store (DB or in-memory cache) for refresh tokens

1. Issue Access & Refresh Tokens on Login

In pages/api/login.js, validate users via WordPress, then sign and set two cookies:

This issues a short-lived access_token cookie and a longer-lived refresh_token cookie, both inaccessible to JavaScript.

2. Verify Tokens in GraphQL Middleware

In pages/api/graphql.js, parse cookies, verify tokens, and inject context.user:

Your resolvers can now guard data based on context.user.role for both SPAs and Next.js pages.

3. React SPAs: Unified Auth Context

In both seller and customer apps, wrap your app in AuthProvider:

Use credentials: 'include' everywhere so cookies travel automatically.

4. Refresh Tokens: Rotate & Retry

Refresh Endpoint (pages/api/refresh.js)

Client Retry Logic (src/fetchWithRefresh.js)

This ensures seamless background rotation and automatic retry of failed requests.

5. Logout & Expiry Flow

Logout Endpoint (pages/api/logout.js)

Client Logout

Use this on your logout buttons to clear cookies and revoke server-side tokens.

Conclusion

By consolidating access and refresh tokens into HTTP-only cookies, rotating on each use, and providing a clear logout strategy, the E-Commerce platform will benefit from:

  • Strong XSS Protection: JavaScript can’t access your tokens
  • CSRF Defense: leveraging SameSite and optional double-submit tokens
  • Seamless UX: single sign-on across Next.js and both React SPAs
  • Robust Session Management: short-lived access, long-lived refresh, and forced logout flows

Leave a Reply

Your email address will not be published. Required fields are marked *