ErrorPro / react-google-autocomplete

React components for google places API.
MIT License
462 stars 114 forks source link

google is not defined on NextJS production #226

Closed JNuno007 closed 9 months ago

JNuno007 commented 9 months ago

Hi guys, I am having issues regarding having access to google global variable at the comment where I inject the google script.

I am using the usePlacesService where add the apiKey like the following:

const {
    placesService,
    placePredictions,
    getPlacePredictions,
    isPlacePredictionsLoading,
    autocompleteSessionToken,
    refreshSessionToken,
  } = usePlacesService({
    apiKey: process.env.NEXT_PUBLIC_GOOGLE_API,
    debounce: 350,
    sessionToken: true,
  });

Is there something I am missing? Locally, in dev mode or running prod mode through a build, it works fine. The NextJS server is running behind an NGINX server. Inspecting the browser, in locally I can see the google script being injected when the component is called. At prod mode, it is not.

Thanks in advance

jv18creator commented 9 months ago

Have you added Script in your layout?

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <Script
        type="text/javascript"
        src={`https://maps.googleapis.com/maps/api/js?key=${process.env.NEXT_PUBLIC_GOOGLE_PLACES_API}&libraries=places`}
      />
      <body>{children}</body>
    </html>
  )
}
JNuno007 commented 9 months ago

Hi, just checked and the problem was that I had the Google API key in the env file, however I am using circleCI to deploy to my VPS, and I need to add the key to the circleCI project settings too. The usePlaceService injects the script automatically so all is good. Thank you for the feedback!