← Back to list

React. Google Place API — how to fix CORS issue.

Hi! I am a Junior Front End React developer. Recently I got one quite simple (as I thought) task:

Anna Novik · 2022-07-26 10:29 · 3 claps · 2.9 min read
#react #google-places #autocomplete #cors #error
Open on Medium ↗
Wiki topics: 🌐 · Web Development

React. Google Place API — how to fix CORS issue.

Hi! I am a Junior Front End React developer. Recently I got one quite simple (as I thought) task:

| Get countries` names using Google Places Autocomplete API.

So I just send a Place Autocomplete request

https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Ukraine&types=(regions)&key=MY_KEY&language=en

… and got an error:

Access to fetch has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

Access to fetch has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

Tons of searching showed me that a lot of developers got this issue. I have spent some time finding a working solution and want to share it.

Main what we need to know

  1. Google Places API is created for server-side applications. That’s probably why appropriate CORS response headers are not set by the server.
  2. For using Google Places Autocomplete on the client-side we need AutocompleteService from Places Library in Google Maps JavaScript API.
  3. Here are google docs about: places, places-autocomplete, places-autocomplete-service

Solution

  1. Get your API key

Here is the guide: https://developers.google.com/maps/documentation/javascript/get-api-key

2. Enable Maps JavaScript API and Places API

Here gide is: https://support.google.com/googleapi/answer/6158841?hl=en

3. Loading the library

The Places service is a self-contained library, separate from the main Maps JavaScript API code. To use the functionality contained within this library, you must first load it using the libraries parameter in the Maps API bootstrap URL:

<script async src=”https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
</script>

You can paste it into the index.html file.

4. Implement AutocompleteService

First, decide what component you will use for autocomplete. I use the library react-bootstrap-typeahead. Check the code above. All magic happens in the handleCountryAutocomplete function.

import "react-bootstrap-typeahead/css/Typeahead.css";
import { useState } from "react";
import { AsyncTypeahead } from "react-bootstrap-typeahead";
export default function App() {
const [countriesAutocompleteList, setCountriesAutocompleteList] =  useState([]);
const [isCountryChanging, setIsCountryChanging] = useState(false);
const [searchingCountry, setSearchingCountry] = useState(false);
const handleCountryAutocomplete = async (text) => {
  setSearchingCountry(true);
  setIsCountryChanging(true);
  const displaySuggestions = async (predictions, status) => {
  if ( status !== google.maps.places.PlacesServiceStatus.OK || !predictions ) return;
  const countriesNames = predictions.map((item) => ({
    id: item.place_id,
    countryName: item.description
  }));
  setCountriesAutocompleteList(countriesNames);
};
try {
  new google.maps.places.AutocompleteService().getPlacePredictions(
{ input: text, types: ["country"] }, displaySuggestions );
} catch (error) {
  console.log(error);
} finally {
  setSearchingCountry(false);
}
};
return (
<div className="App">
<AsyncTypeahead
  id="country-typeahead"
  useCache={false}
  isLoading={searchingCountry}
  labelKey="countryName"
  options={countriesAutocompleteList}
  onChange={(item) => console.log(item)}
  onSearch={(query) => handleCountryAutocomplete(query)}
/>
</div>
);
}

5. Handle country selection.

All that is left is to handle country selection. It is implemented in the handleCountrySearchSelection function.

So the code of solving the task which was given to us:

import "react-bootstrap-typeahead/css/Typeahead.css";
import "./styles.scss";
import { useState } from "react";
import { Form } from "react-bootstrap";
import { AsyncTypeahead } from "react-bootstrap-typeahead";
export default function App() {
  const [countriesAutocompleteList, setCountriesAutocompleteList] =  useState([]);
  const [selectedCountry, setSelectedCountry] = useState([]);
  const [isCountryChanging, setIsCountryChanging] = useState(false);
  const [searchingCountry, setSearchingCountry] = useState(false);
  const handleCountrySearchSelection = async (item) => {
    if (!item.length) {
      setIsCountryChanging(true);
      setSelectedCountry([]);
    } else {
      setSelectedCountry([{ countryName: item[0].countryName }]);
      setIsCountryChanging(false);
    }
  };
  const handleCountryAutocomplete = async (text) => {
   setSearchingCountry(true);
   setIsCountryChanging(true);
   const displaySuggestions = async (predictions, status) => {
     if ( status !== google.maps.places.PlacesServiceStatus.OK || !predictions ) return;
     const countriesNames = predictions.map((item) => ({
       id: item.place_id,
       countryName: item.description
     }));
     setCountriesAutocompleteList(countriesNames);
   };
   try {
   new google.maps.places.AutocompleteService().getPlacePredictions(
{ input: text, types: ["country"] }, displaySuggestions );
   } catch (error) {
      console.log(error);
   } finally {
     setSearchingCountry(false);
   }
 };
return (
<div className="App">
  <h2>For making some magic happen set API key in index.html!</h2>
  <h4>
    <span>More details: </span>
    <a href="https://developers.google.com/maps/documentation/javascript/get-api-key">google documentation</a>
  </h4>
  <Form.Group controlId="formGroupCountry">
    <Form.Label>
      <div>Country </div>
    </Form.Label>
    <div className="d-flex">
    <AsyncTypeahead
      id="country-typeahead"
      useCache={false}
      isLoading={searchingCountry}
      labelKey="countryName"
      options={countriesAutocompleteList}
      selected={selectedCountry}
      onChange={(item) => handleCountrySearchSelection(item)}
      onSearch={(query) => handleCountryAutocomplete(query)}
    />
    <div>
      { isCountryChanging ? (
        <span className="error">Select from the list</span>
       ) : null}
    </div>
    </div>
  </Form.Group>
</div>
);
}

Thanks to using AutocompleteService from Places Library I don’t get CORS error anymore.

I hope this will help you too.

Also, you can check it out on codeSandbox.


메타데이터
post_id
efa7a7d41e41
slug
react-google-place-api-how-to-fix-cors-issue-efa7a7d41e41
url
https://medium.com/@anna.novik/react-google-place-api-how-to-fix-cors-issue-efa7a7d41e41
canonical_url
https://medium.com/@anna.novik/react-google-place-api-how-to-fix-cors-issue-efa7a7d41e41
author_url
https://medium.com/@anna.novik
status
ok
fetched_at
2026-08-10 12:41:46