Guides
How to Add Google Maps to Next.js
Google Maps is inherently interactive, so the map component itself has to be a client component — this covers loading it correctly and keeping the API key secure.
Prerequisites
- arrow_rightA Google Cloud project with the Maps JavaScript API enabled
- arrow_rightAn API key restricted to your domain
Step 1: Secure the API Key
In the Google Cloud Console, restrict the API key to your site's domain(s) under Application restrictions, and limit it to only the specific Maps APIs you actually use — this prevents the key from being abused if it's exposed in client-side code, which it necessarily will be for a browser-rendered map.
Step 2: Load the Map in a Client Component
components/Map.tsx
'use client';
import { APIProvider, Map } from '@vis.gl/react-google-maps';
export default function LocationMap() {
return (
<APIProvider apiKey={process.env.NEXT_PUBLIC_MAPS_API_KEY!}>
<Map defaultCenter={{ lat: 25.2, lng: 55.3 }} defaultZoom={11} style={{ height: '400px' }} />
</APIProvider>
);
}Step 3: Use It in a Server-Rendered Page
The rest of the page — surrounding content, metadata — stays server-rendered as normal; only the map component itself needs 'use client', since it's the only part requiring browser APIs.
Common Errors
- arrow_rightMap fails to load with a 'RefererNotAllowedMapError' — the API key's domain restrictions don't include the current domain (including localhost during development)
- arrow_rightMap container renders with zero height — the container needs an explicit height, since the map has no natural content to size itself against
- arrow_rightBilling errors — Google Maps requires a billing account attached to the project, even within the free usage tier
Performance Considerations
- arrow_rightLazy-load the map component below the fold using dynamic import with ssr: false, since it's client-only anyway and shouldn't block initial page render
- arrow_rightDebounce any autocomplete or search-as-you-type interactions to avoid excessive API requests
Frequently Asked Questions
Is it safe to expose the Maps API key in client code?add
Yes, as long as it's properly restricted by domain (HTTP referrer) and limited to specific APIs in the Google Cloud Console — the key is meant to be public-facing for browser-based maps, and restrictions are what actually prevent abuse.
Can I use a free alternative instead?add
Leaflet with OpenStreetMap tiles is a free option for basic map display, without Google's Places autocomplete or Directions data — see the Google Maps API integration page for a fuller comparison.
Why does the map need to be a client component?add
The Maps JavaScript API is inherently interactive and runs in the browser — it can't be rendered server-side, so any component using it needs 'use client'.