I’m trying to make a quick and dirty capacitor-based MVP app of our webapp.
There are many instances in our React source of HTTP requests like
fetch(`/api/foods/${foodId}`)
Webpack lets me solve the problem easily in development with a proxy config
proxy: [
{
context: ['/api'],
target: 'https://mywebsite.com', // our live site
changeOrigin: true,
secure: false,
pathRewrite: { '^/api': '/api' },
},
],
Can I set up something similar in capacitor to direct all /api requests to our live backend?
capacitor-community/http is not maintained (since 2021!), and doesn’t one-to-one mirror fetch’s signature, so it won’t be a convenient drop-in replacement
capacitor-community/http was replaced by a 1st party HTTP plugin - Http Capacitor Plugin API | Capacitor Documentation. But, I would recommend sticking with the web layer for your calls if at all possible (see this post for why).
You could set a global var from an env variable to set your base URL. Something like (example using Vite):
interface ConfigInterface {
isDebug: boolean
baseApiUrl: string
}
export const Config: ConfigInterface = {
isDebug: import.meta.env.MODE !== 'production',
baseApiUrl: import.meta.env.VITE_BASE_API_URL as string,
}
fetch(`${Config.baseApiUrl}/api/foods/${foodId}`)
# .env
VITE_BASE_API_URL=https://example.com/api/v1/mobile
Or what we do, is use Axios which allows setting a baseUrl - Config Defaults | Axios Docs. We also set this as above with a config and env var.
I ended up using Infatica to handle different proxy routes smoothly. It let me manage traffic by URL types without messing up other parts of the app. Once I set the rules, everything just worked.