frontend: derive the dev API base URL from the Metro host
Development builds had to hardcode the current machine's LAN IP in .env.development.local, so the value moved per machine and per network. When EXPO_PUBLIC_API_BASE_URL is unset the client now takes the host from Constants.expoConfig.hostUri and assumes port 3000, which follows whichever host the dev client already talks to; release builds have no hostUri, so the env var still covers them
Pedro Lucas Porcellis porcellis@eletrotupi.com · 13 days ago
37df513ec523141502d830ba76573cee4dcf928a Browse filesParents
7eac2b0Changed files
2
Additions
+13
Deletions
-3
frontend/.env.example
1 1
# Bundle-time env for Expo (inlined by Metro; keep values device-reachable).
2 2
# Copy to .env.local (gitignored) or export before `npx expo start`.
3 3
#
4 4
# Never put a secret here: EXPO_PUBLIC_* ends up inside the shipped JS bundle.
5 5
#
6 -
# LAN IP of the machine running the API (see frontend/scripts/e2e.sh print-env).
7 -
EXPO_PUBLIC_API_BASE_URL=http://192.168.1.10:3000
6 +
# Optional in development. When unset, the app derives the API host from the
7 +
# Metro server it is already talking to (localhost under `npm run
8 +
# android:reverse`, otherwise the LAN IP) and assumes port 3000. Release builds
9 +
# have no Metro host, so they need this set per EAS environment instead.
10 +
# EXPO_PUBLIC_API_BASE_URL=http://192.168.1.10:3000
8 11
# SecureStore key under which the JWT is persisted.
9 12
EXPO_PUBLIC_TOKEN_KEY=orbit-jwtfrontend/lib/api/client.ts
1 1
import * as SecureStore from "expo-secure-store";
2 +
import Constants from "expo-constants";
2 3
3 4
export class ApiError extends Error {
4 5
status: number;
5 6
fields?: Record<string, string>;
6 7
52 53
AvatarResponse,
53 54
RemoveAvatarResponse,
54 55
ExportDataResponse,
55 56
} from "@/lib/api/types";
56 57
57 -
const API_BASE_URL = process.env.EXPO_PUBLIC_API_BASE_URL;
58 +
// Development builds already talk to Metro, so the API is on the same host.
59 +
// Release builds have no hostUri and always take the env var.
60 +
const API_BASE_URL =
61 +
process.env.EXPO_PUBLIC_API_BASE_URL ??
62 +
(Constants.expoConfig?.hostUri
63 +
? `http://${Constants.expoConfig.hostUri.split(":")[0]}:3000`
64 +
: undefined);
58 65
const TOKEN_KEY = process.env.EXPO_PUBLIC_TOKEN_KEY;
59 66
60 67
class ApiClient {
61 68
private onUnauthorizedCallback?: () => void;
62 69
518 525
return response.arrayBuffer()
519 526
}
520 527
}
521 528
522 529
export const apiClient = new ApiClient();