Onboarding welcome screen showed a text "Continue with GitHub" button even though NEXT_PUBLIC_GITHUB_CLIENT_ID is unset in prod (nothing to connect to) -- now hidden entirely when unconfigured, icon-only when it is (Apple-design icon-only-chrome rule). Also hoisted the public-path allowlist (middleware's auth gate + the API client's 401-redirect) into one shared apps/ritgram/web/lib/publicPaths.ts so the two definitions can't drift: the 401 interceptor previously hard-redirected any cookie-less visitor on a public page (e.g. /explore's best-effort "recommended for you" call) straight to /login before the page's own try/catch ever ran. ContentComposer's submit button is icon-only too, same rule, with an aria-label/title carrying the real action text for accessibility. tsc --noEmit clean. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
123 lines
4.4 KiB
TypeScript
123 lines
4.4 KiB
TypeScript
import axios, { AxiosError } from 'axios'
|
|
import { isPublicPath } from '@/lib/publicPaths'
|
|
|
|
const MAX_RETRIES = 3
|
|
const RETRY_DELAY = 1000 // 1 second
|
|
const API_VERSION_PREFIX = '/v1'
|
|
|
|
function normalizeApiPath(url?: string) {
|
|
if (!url) return url
|
|
if (/^https?:\/\//i.test(url)) return url
|
|
|
|
const normalized = url.startsWith('/') ? url : `/${url}`
|
|
if (normalized === API_VERSION_PREFIX || normalized.startsWith(`${API_VERSION_PREFIX}/`)) {
|
|
return normalized
|
|
}
|
|
|
|
return `${API_VERSION_PREFIX}${normalized}`
|
|
}
|
|
|
|
const api = axios.create({
|
|
baseURL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000/api',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
withCredentials: true, // Send httpOnly cookies automatically
|
|
timeout: 30000, // 30 second timeout
|
|
})
|
|
|
|
// Helper to check if error is retryable
|
|
const isRetryableError = (error: AxiosError) => {
|
|
// Retry on network errors or 5xx server errors
|
|
if (!error.response) return true // Network error
|
|
const status = error.response.status
|
|
return status >= 500 && status < 600
|
|
}
|
|
|
|
// Helper to sleep
|
|
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
|
|
|
|
// Helper to refresh token (cookies are sent automatically)
|
|
const refreshAccessToken = async (): Promise<boolean> => {
|
|
try {
|
|
await axios.post(
|
|
`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000/api'}${normalizeApiPath('/auth/refresh')}`,
|
|
{},
|
|
{ withCredentials: true }
|
|
)
|
|
return true
|
|
} catch {
|
|
return false
|
|
}
|
|
}
|
|
|
|
// No request interceptor needed — cookies are sent automatically via withCredentials
|
|
api.interceptors.request.use((config) => {
|
|
config.url = normalizeApiPath(config.url)
|
|
return config
|
|
})
|
|
|
|
api.interceptors.response.use(
|
|
(response) => response,
|
|
async (error: AxiosError) => {
|
|
const originalRequest = error.config as any
|
|
|
|
if (!originalRequest) {
|
|
return Promise.reject(error)
|
|
}
|
|
|
|
// Initialize retry count
|
|
originalRequest._retryCount = originalRequest._retryCount || 0
|
|
|
|
// The global AuthBootstrap (app/providers.tsx) calls GET /auth/me on every
|
|
// page load, on every route, public or not, to silently populate auth
|
|
// state. For a signed-out visitor this 401 is the normal, expected
|
|
// result -- not a session that needs recovering -- so it must never
|
|
// trigger the hard redirect below. Without this guard, every anonymous
|
|
// visit to any page (including /login and /register themselves) forced
|
|
// a `window.location.href = '/login'` a second or two after load: the
|
|
// reload re-ran AuthBootstrap, 401'd again, and redirected again,
|
|
// forever. Found live 2026-11-17 while verifying the design pass --
|
|
// confirmed via a fresh, cookie-less browser context repeatedly bounced
|
|
// from /register to /login in a loop.
|
|
const isAuthCheckRequest = typeof originalRequest.url === 'string' &&
|
|
(originalRequest.url.includes('/auth/me') || originalRequest.url.includes('/auth/refresh'))
|
|
|
|
// Handle 401 unauthorized - try token refresh
|
|
if (error.response?.status === 401 && !originalRequest._retry && !isAuthCheckRequest) {
|
|
originalRequest._retry = true
|
|
|
|
const refreshed = await refreshAccessToken()
|
|
if (refreshed) {
|
|
return api(originalRequest)
|
|
}
|
|
|
|
// Refresh failed. Only force-navigate away on pages that actually
|
|
// require a session — public pages (/, /explore, /docs, a public
|
|
// profile, ...) make best-effort authenticated calls (e.g. explore's
|
|
// "recommended for you") that are expected to 401 for anonymous
|
|
// visitors and already fail silently in their own try/catch. Hard-
|
|
// redirecting those visitors to /login was a real bug: it fired
|
|
// `window.location.href` before the page's own catch block ever ran,
|
|
// bouncing cookie-less /explore visitors to /login. Found 2026-11-17.
|
|
const pathname = typeof window !== 'undefined' ? window.location.pathname : undefined
|
|
if (pathname !== undefined && !isPublicPath(pathname)) {
|
|
window.location.href = '/login'
|
|
}
|
|
}
|
|
|
|
// Handle retryable errors (network issues, 5xx)
|
|
if (isRetryableError(error) && originalRequest._retryCount < MAX_RETRIES) {
|
|
originalRequest._retryCount += 1
|
|
|
|
// Exponential backoff
|
|
const delay = RETRY_DELAY * Math.pow(2, originalRequest._retryCount - 1)
|
|
await sleep(delay)
|
|
|
|
return api(originalRequest)
|
|
}
|
|
|
|
return Promise.reject(error)
|
|
}
|
|
)
|
|
|
|
export default api
|