Ilyas Ghomrani
Ilyas Ghomrani

Reputation: 479

Handling environment variables in SSR with Angular Universal

I'm applying SSR to a pre-existing Angular project. In the previous Client Side Rendering CSR implementation, I used the global variable window to handle ENV VARS for one build - multiple deployments CI/CD purposes following this article.

I tried using a custom service to pass the env vars to app.modules.ts using the APP_INITIALIZER with no success because the usage of envirement with forRoot() will be called way before my service. Also, webpack can't help in this situation because of one build - multiple deployments requirment.

As the example bellow I tried to inject the EnvironmentService in a module but it seems that data isn't fetched yet from the file as metioned in the article above.

import { EnvironmentService } from './environments/EnvironmentService';

let envService: EnvironmentService;

@NgModule({
    declarations: [...],
    imports: [ServerLogModule.forRoot(envService.ENV_VARS)],
    providers: [...]
})
export class AppModule {}

Upvotes: 4

Views: 3843

Answers (1)

gmerwan
gmerwan

Reputation: 145

• Passing an environment variable to forRoot() method from another service in app.modules.ts's providers won't be possible since you won't be able to retrieve any data before the method is called.

In order for this to work, it's better to use webpack to create at build time an environment.ts file with the correct data, and use it in app.modules.ts this may help

• The article mentioned in your question -as you said- would work very well for a Client Side Rendering situation, but using the same approach for SSR may require lots of changes for some/many architectural choices you may have already made.

Upvotes: 3

Related Questions