I faced a problem that I couldn't use vercel environment variables with a deployed angular app. I used to write my sensitive information in an env file while writing backend code and I forgot that browsers don't support the process
module. So I searched for a while and got the result I want by following these steps:
- install the next package:
npm install --save-dev @angular-builders/custom-webpack
- open
angular.json
and use"builder": "@angular-builders/custom-webpack:browser"
instead of"builder": "@angular-devkit/build-angular:browser"
- add
customWebpackConfig
key inoptions
object with a path to a file that you will create later:"options": { "customWebpackConfig": {"path": "custom-webpack-config.js"} }
- create a new file in the root directory with the name
custom-webpack-config.js
and add this code in it:const webpack = require("webpack"); module.exports = { plugins: [ new webpack.DefinePlugin({ $env: { API_KEY: JSON.stringify(process.env.API_KEY), LOCATION_API_KEY: JSON.stringify(process.env.LOCATION_API_KEY), }, }), ], };
- and create another file in the src directory with the name
typing.d.ts
and this code in it:import { CoreEnvironment } from '@angular/compiler/src/compiler_facade_interface'; declare var $env: ENV; interface ENV { API_KEY: string; LOCATION_API_KEY: string; }
- now add the vars to the
environment.prod.ts
file and use them as you want around the project:import { $env } from 'src/typing.d'; export const environment = { production: true, API_KEY: $env.API_KEY, LOCATION_API_KEY: $env.LOCATION_API_KEY, };