Firebase多站点托管场景下如何按不同环境部署Next.js应用
Firebase多环境多站点部署Next.js Function 实操步骤
1. 绑定本地部署目标与对应环境的Hosting站点
在项目根目录执行以下命令,将三套环境的Hosting站点和本地部署别名绑定,<站点ID>替换为你在Firebase控制台创建的对应环境站点的唯一ID:
- 绑定开发环境:
firebase target:apply hosting dev <dev环境站点ID> - 绑定预发环境:
firebase target:apply hosting stage <stage环境站点ID> - 绑定生产环境:
firebase target:apply hosting live <live环境站点ID>
2. 配置firebase.json适配多环境
在firebase.json中配置多套hosting规则,同时将不同环境的请求rewrite到对应环境的Next.js Function上,示例配置如下:
{ "hosting": [ { "target": "dev", "public": ".next/static", "ignore": ["firebase.json", "**/.*", "**/node_modules/**"], "rewrites": [ { "source": "**", "function": "nextjs-dev" } ] }, { "target": "stage", "public": ".next/static", "ignore": ["firebase.json", "**/.*", "**/node_modules/**"], "rewrites": [ { "source": "**", "function": "nextjs-stage" } ] }, { "target": "live", "public": ".next/static", "ignore": ["firebase.json", "**/.*", "**/node_modules/**"], "rewrites": [ { "source": "**", "function": "nextjs-live" } ] } ], "functions": [ { "source": "functions", "codebase": "default", "ignore": [".git", "node_modules", ".firebase"] } ] }
如果使用官方Firebase Next.js集成工具,不需要手动配置rewrite,工具会自动根据部署环境生成对应Function
3. 拆分环境变量
为三套环境分别创建环境变量配置文件,比如.env.dev、.env.stage、.env.live,存储对应环境的接口地址、第三方服务密钥等配置,部署前先加载对应环境的变量再执行Next.js构建。
如果需要给Function配置环境变量,可以使用Firebase官方的环境配置命令,按环境区分设置:
# 开发环境变量设置 firebase functions:config:set dev.env_key="xxx" --project <dev项目ID> # 预发环境变量设置 firebase functions:config:set stage.env_key="xxx" --project <stage项目ID> # 生产环境变量设置 firebase functions:config:set live.env_key="xxx" --project <live项目ID>
4. 按环境执行部署命令
部署时指定对应环境的hosting和Function即可:
- 部署开发环境:
firebase deploy --only hosting:dev,functions:nextjs-dev - 部署预发环境:
firebase deploy --only hosting:stage,functions:nextjs-stage - 部署生产环境:
firebase deploy --only hosting:live,functions:nextjs-live
如果三套环境对应三个独立的Firebase项目,部署时额外添加--project <对应项目ID>参数即可隔离环境资源
内容的提问来源于stack exchange,提问作者undefined
相关产品推荐
相关产品推荐

