Vercel部署Next.js应用遇Google Maps InvalidKeyMapError问题求助
解决Vercel部署Next.js Google Maps InvalidKeyMapError问题
问题重现
本地运行Next.js应用,使用@react-google-maps/api实现地图功能正常,但部署到Vercel后出现Google Maps JavaScript API error: InvalidKeyMapError,提示API密钥无效。已配置环境变量且密钥设置为无限制。
相关代码
GoogleMap组件:
import React, { useContext } from "react"; import { GoogleMap, LoadScript } from "@react-google-maps/api"; import { UserLocationContext } from "../context/UserLocationContext"; import Marker from "./Marker"; import { SelectedBusinessContext } from "../context/SelectedBusinessContext"; function GoogleMap_() { const { userLocation, setUserLocation } = useContext(UserLocationContext); const { selectedBusiness, setSelectedBusiness } = useContext( SelectedBusinessContext ); const containerStyle = { width: "100%", height: "500px", borderRadius: 20, }; return ( <div> <LoadScript googleMapsApiKey={process.env.NEXT_PUBLIC_GOOGLE_API_KEY}> {userLocation ? ( <GoogleMap mapContainerStyle={containerStyle} center={ !selectedBusiness.name ? { lat: parseFloat(userLocation.lat), lng: parseFloat(userLocation.lng), } : selectedBusiness.geometry.location } zoom={selectedBusiness.name ? 15 : 10} > <> <Marker userLocation={userLocation} /> </> </GoogleMap> ) : null} </LoadScript> </div> ); } export default GoogleMap_;
.env文件:
GOOGLE_API_KEY="A...E" NEXT_PUBLIC_GOOGLE_API_KEY=A...E
解决方案
1. 检查Vercel环境变量配置
- 登录Vercel控制台,进入对应项目的Settings > Environment Variables,添加
NEXT_PUBLIC_GOOGLE_API_KEY变量,值直接填密钥(不要加引号)。本地.env中如果带引号,Next.js会自动解析,但Vercel中输入引号会被当作密钥的一部分,导致无效。 - 确保变量设置为Production环境(或所有环境),部署时能被正确读取。
2. 强制重新构建部署
Next.js的NEXT_PUBLIC_前缀变量是构建时注入的,若Vercel使用了旧的缓存构建产物,新环境变量不会生效:
- 在Vercel的部署记录中,点击对应部署的Redeploy按钮,取消勾选"Redeploy with existing Build Cache",强制重新构建。
3. 验证Google Cloud API状态
- 登录Google Cloud控制台,确认Maps JavaScript API已启用(搜索API名称,查看状态为"Enabled")。即使密钥无限制,未启用对应API也会触发无效密钥错误。
- 直接访问
https://maps.googleapis.com/maps/api/js?key=你的密钥,若返回正常的JS代码则密钥有效;若返回"API not enabled"类错误,需启用对应API。
4. 确认环境变量加载状态
在GoogleMap组件中临时添加日志,部署后查看浏览器控制台:
console.log("API Key:", process.env.NEXT_PUBLIC_GOOGLE_API_KEY);
- 若输出
undefined:说明Vercel环境变量未配置正确; - 若输出带引号的密钥:说明Vercel中变量值加了引号,需去掉引号重新配置。
内容的提问来源于stack exchange,提问作者Ant1ne
相关产品推荐
相关产品推荐

