Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/lib/api-unauthorized.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { describe, expect, it } from 'vitest';
import { ApiError, isUnauthorized, NetworkError } from './api';

describe('isUnauthorized (#42)', () => {
it('is true only for a 401 ApiError', () => {
expect(isUnauthorized(new ApiError('Unauthorized', 401))).toBe(true);
});

it('keeps the token for other failures', () => {
expect(isUnauthorized(new ApiError('Forbidden', 403))).toBe(false);
expect(isUnauthorized(new ApiError('Server error', 500))).toBe(false);
expect(isUnauthorized(new NetworkError('Could not reach the server.'))).toBe(false);
expect(isUnauthorized(new Error('boom'))).toBe(false);
});
});
5 changes: 5 additions & 0 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ export class NetworkError extends ApiError {
/** Default per-request timeout; override with `RequestOptions.timeoutMs`. */
export const DEFAULT_TIMEOUT_MS = 15_000;

/** True when the backend rejected our credentials (expired / invalid JWT). */
export function isUnauthorized(err: unknown): boolean {
return err instanceof ApiError && err.status === 401;
}

export function getToken(): string | null {
if (typeof window === 'undefined') return null;
return window.localStorage.getItem(TOKEN_KEY);
Expand Down
14 changes: 12 additions & 2 deletions src/lib/auth-context.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use client';

import { createContext, useCallback, useContext, useEffect, useState } from 'react';
import { apiFetch, clearToken, setToken } from './api';
import { apiFetch, clearToken, getToken, isUnauthorized, setToken } from './api';
import type { Me } from './types';

interface AuthResponse {
Expand All @@ -25,10 +25,20 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
const [loading, setLoading] = useState(true);

const refresh = useCallback(async () => {
// No stored token: we're signed out, so skip the /users/me round-trip
// that would only fail on every page load (#42).
if (!getToken()) {
setUser(null);
return;
}
try {
const me = await apiFetch<Me>('/users/me');
setUser(me);
} catch {
} catch (err) {
// A 401 means the stored JWT is expired or invalid: drop it so later
// requests stop sending a dead Authorization header (#42). Other
// failures (network, 5xx) keep the token — the session may be fine.
if (isUnauthorized(err)) clearToken();
setUser(null);
}
}, []);
Expand Down
Loading