SSR takes wrong environment in Angular
I have solved this problem. You need to check your angular.json file. In the server section, you need "server": {
"builder": "@angular-devkit/build-angular:server",
"options": {
"outputPath": "./dist/server",
"main": "./src/client/main.server.ts",
"tsConfig": "./src/client/tsconfig.server.json"
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/client/environments/environment.ts",
"with": "src/client/environments/environment.prod.ts"
}
]
},
"cloud": {
"fileReplacements": [
{
"replace": "src/client/environments/environment.ts",
"with": "src/client/environments/environment.cloud.ts"
}
]
}
}
}
- Create configuration for server build in angular.json
Sample Code: "server": {
"builder": "@angular-devkit/build-angular:server",
"options": {
"outputPath": "dist/server",
"main": "src/main.server.ts",
"tsConfig": "src/tsconfig.server.json"
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
}
}
}
- Edit package.json to use the above created build configuration. As per angular documentation, There must be a key named "build:client-and-server-bundles" in scripts object. Modify "ng build --prod && ng run app:server" to "ng build --prod && ng run app:server -c production".
Sample code:
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"build:ssr": "npm run build:client-and-server-bundles && npm run webpack:server",
"serve:ssr": "node dist/server",
"build:client-and-server-bundles": "ng build --prod && ng run app:server -c production",
"webpack:server": "webpack --config webpack.server.config.js --progress --colors"
}