Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
5 changes: 4 additions & 1 deletion apps/web/hooks/useAuth.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useState } from 'react';
import { useWalletStore } from '@/store/wallet';
import { signTransaction } from '@stellar/freighter-api';
import { fetchChallenge, verifyChallenge } from '@/lib/api';
import { fetchChallenge, verifyChallenge, initApiClientWithToken } from '@/lib/api';

/**
* Custom hook for authenticating the connected Stellar wallet via SEP-10.
Expand Down Expand Up @@ -60,10 +60,12 @@ export function useAuth() {
// 3. Submit signed challenge to verify and receive JWT
const { token: jwt } = await verifyChallenge(signedXdr);
setToken(jwt);
initApiClientWithToken();
} catch (err: unknown) {
const message = err instanceof Error ? err.message : 'Authentication failed';
setError(message);
setToken(null);
initApiClientWithToken();
} finally {
setLoading(false);
}
Expand All @@ -74,6 +76,7 @@ export function useAuth() {
*/
const logout = () => {
setToken(null);
initApiClientWithToken();
disconnect();
};

Expand Down
9 changes: 8 additions & 1 deletion apps/web/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,15 @@ const getApiUrl = () => {
return process.env.NEXT_PUBLIC_INDEXER_API_URL || 'http://localhost:8080';
};

async function apiFetch<T>(path: string, options: RequestInit = {}): Promise<T> {
let cachedToken: string | null = null;

export function initApiClientWithToken(): void {
const token = useWalletStore.getState().token;
cachedToken = token;
}

async function apiFetch<T>(path: string, options: RequestInit = {}): Promise<T> {
const token = cachedToken || useWalletStore.getState().token;
const headers = new Headers(options.headers || {});

if (token) {
Expand Down