You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NestJS服务端向React应用注入环境变量替换__CONFIG__占位符

实现方案

因为默认ServeStaticModule会直接返回静态文件,不会处理内容修改,所以你需要加一层自定义逻辑处理index.html的返回,核心步骤如下:


步骤1:调整ServeStaticModule配置

排除index.html的默认返回,把根路径请求留给自定义逻辑处理:

import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';

@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', 'client'), // 替换为你React打包产物的实际存放路径
      exclude: ['/'], // 排除根路径请求,不走默认静态资源返回逻辑
    }),
    // 其他模块引入
  ]
})

步骤2:编写请求处理逻辑替换占位符

新增通配符接口读取index.html内容,替换占位符后再返回给客户端:

import { Controller, Get, Res } from '@nestjs/common';
import { Response } from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';
import { ConfigService } from '@nestjs/config'; // 你项目中用来读取服务端配置的服务

@Controller()
export class AppController {
  constructor(private configService: ConfigService) {}

  // 通配符匹配所有未命中静态资源的GET请求,同时适配SPA前端history路由模式
  @Get('*')
  serveIndexHtml(@Res() res: Response) {
    // 读取本地打包好的index.html原始内容
    const indexPath = join(__dirname, '..', 'client', 'index.html');
    let htmlContent = readFileSync(indexPath, 'utf-8');

    // 组装要注入到客户端的配置项
    const clientConfig = {
      analyticsUrl: this.configService.get('ANALYTICS_SERVICE_URL'),
      clientId: this.configService.get('OAUTH_CLIENT_ID'),
      redirectUrl: this.configService.get('OAUTH_REDIRECT_URL'),
      // 其他需要暴露给客户端的配置
    };

    // 替换占位符,直接把配置对象序列化为JSON字符串插入即可
    htmlContent = htmlContent.replace('__CONFIG__', JSON.stringify(clientConfig));

    // 返回处理后的HTML
    res.setHeader('Content-Type', 'text/html');
    res.send(htmlContent);
  }
}

可选优化

如果配置不会动态更新,可以把读取到的原始HTML内容、替换后的结果做内存缓存,避免每次请求都重复读文件和执行替换逻辑,提升响应性能。


注意事项

  • 不要往配置里插入服务端密钥、数据库密码等敏感信息,配置会直接暴露到客户端源码中
  • 如果配置项包含用户可控的内容,建议先对值做XSS转义再注入,避免安全风险
  • 如果你用的是Fastify适配器,只需要对应调整响应返回的API即可,核心替换逻辑不变

内容的提问来源于stack exchange,提问作者Liav Nave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 04:15:09