MapKit: Getting Started with Secure API Keys

Set Up Your Google Maps API Key Securely

Make sure your API keys are safe and secure before starting your projects!

1

Get a Google Maps API Key

Go to the Google Cloud Console, create a new project, and enable the Maps JavaScript API.

2

Restrict Your API Key

In the Cloud Console under Credentials, add HTTP referrer restrictions (e.g., websitename.com) and enable only the required APIs for your project.

3

Store the API Key in a Server Environment Variable

Create a .env file in your backend project root and add:

GOOGLE_MAPS_API_KEY = YOUR_API_KEY_HERE

Make sure to add .env to your .gitignore to avoid committing secrets.

4

Serve the API Key Securely via Your Backend

Create a backend API endpoint that returns the API key securely (example using Node.js & Express):


require('dotenv').config();
const express = require('express');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

app.use(express.static(path.join(__dirname)));

app.get('/api-key', (req, res) => {
  res.json({ key: process.env.GOOGLE_MAPS_API_KEY});
});

app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
});
          
5

Load the Google Maps API Script Dynamically on the Frontend

Fetch the API key from your backend and add it to the bottom of your script:


async function loadGoogleMaps() {
  try {
    const response = await fetch('/api-key');
    if (!response.ok) {
      throw new Error('Failed to fetch API key');
    }
    const data = await response.json();

    const script = document.createElement('script');
    script.src = `https://maps.googleapis.com/maps/api/js?key=${data.key}&callback=initMap&libraries=places`;
    script.async = true;
    script.defer = true;
    document.head.appendChild(script);
  } catch (error) {
    console.error("Error loading Google Maps API: ", error);
  }
}

loadGoogleMaps();
          
6

Keep Your API Key Safe

  • Never commit your API key directly to public repositories
  • Use HTTPS for your website
  • Regularly review and restrict API key usage in Google Cloud Console
  • Always always always follow these steps. Better safe than sorry!