Files
homeschool-dashboard/frontend/src/composables/useApi.js
T
derekcandClaude Opus 5.5 3460fff8ff v2026.10.1: keep login redirect, show wrong-password error
The axios 401 interceptor treated failed auth calls (the guard's own
/api/auth/refresh, a wrong-password /api/auth/login) as an expired session
and hard-navigated to a bare /login. That dropped the router guard's
?redirect= and reloaded the login page before its error could show.

- Skip auto-refresh for login/register/refresh
- On a real mid-use expiry, redirect to /login?redirect=<current path>
- LoginView only follows in-app redirect paths

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 23:10:04 -07:00

61 lines
1.8 KiB
JavaScript

import axios from 'axios'
const api = axios.create({
baseURL: '/',
withCredentials: true, // send cookies (refresh token)
})
// Attach access token to every request
api.interceptors.request.use((config) => {
const token = localStorage.getItem('access_token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
// Auto-refresh on 401
let refreshing = false
let waitQueue = []
// These report their own 401s (wrong password, expired refresh cookie); refreshing on them would hide the error
const NO_REFRESH = ['/api/auth/login', '/api/auth/register', '/api/auth/refresh']
api.interceptors.response.use(
(res) => res,
async (error) => {
const original = error.config
if (error.response?.status === 401 && !original._retry && !NO_REFRESH.includes(original.url)) {
if (refreshing) {
return new Promise((resolve, reject) => {
waitQueue.push({ resolve, reject })
}).then(() => api(original))
}
original._retry = true
refreshing = true
try {
const res = await axios.post('/api/auth/refresh', {}, { withCredentials: true })
const token = res.data.access_token
localStorage.setItem('access_token', token)
waitQueue.forEach(({ resolve }) => resolve())
waitQueue = []
original.headers.Authorization = `Bearer ${token}`
return api(original)
} catch (_) {
waitQueue.forEach(({ reject }) => reject())
waitQueue = []
localStorage.removeItem('access_token')
const { pathname, search } = window.location
window.location.href = pathname === '/login'
? '/login'
: `/login?redirect=${encodeURIComponent(pathname + search)}`
} finally {
refreshing = false
}
}
return Promise.reject(error)
}
)
export default api