When using the Google Places Details API in a web browser (including Expo Web), you'll encounter Cross-Origin Resource Sharing (CORS) restrictions. Google's Places API doesn't include the necessary CORS headers to allow direct browser requests, which results in errors like:
Access to fetch at 'https://places.googleapis.com/v1/places/...' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
To work around this limitation, you need to set up a proxy server that:
- Receives requests from your Expo Web application
- Forwards them to the Google Places Details API
- Returns the response back to your application
The proxy server adds the necessary CORS headers to make the browser happy.
We've included an example proxy server in the repository. Here's how to set it up:
Navigate to your project directory and install the required packages:
npm install express axios
# or
yarn add express axiosCopy the example proxy server code from example/places-details-proxy.js to your project. You can place it in your project root or in a server directory.
Start the proxy server:
node places-details-proxy.jsBy default, the server will run at http://localhost:3001.
Update your GooglePlacesTextInput component to use the proxy:
<GooglePlacesTextInput
apiKey="YOUR_GOOGLE_PLACES_API_KEY"
fetchDetails={true}
detailsProxyUrl="http://localhost:3001/places-details"
detailsFields={['formattedAddress', 'location']}
onPlaceSelect={handlePlaceSelect}
/>For production use:
- Deploy the proxy server to a hosting service (like Heroku, Vercel, AWS, etc.)
- Update your
detailsProxyUrlto point to your deployed proxy
When implementing this in production:
- Don't expose your Google API key: Consider validating requests and using your API key on the server side only
- Limit access: Restrict who can use your proxy with authentication or origin checking
- Monitor usage: Keep track of API usage to avoid unexpected costs
By following these steps, you can use Google Places Details API with Expo Web applications effectively.