Running dependent applications created with Nx simultaneously
This is part of a multi-post series detailing how to consume environment variables in an Angular application, replacing the traditional environment.ts
files. The other posts can be found here:
Let’s assume you’ve created two applications called app1
and app2
. app1
is a simple Node application, whereas app2
is an Angular app. app2
has to call app1
and app1
in return serves app2
as static files. In the cloud you let them run on the same server, eliminating the need for any special routing configuration. However, locally you have to run them on different ports to avoid port conflicts as well as to be able to debug them independently.
To be able to run both applications simultaneously we need to execute nx run-many -t serve
. This serves both applications in a single command. However, I’d suggest to add it to your package.json
in scripts
for simplicity:
// package.json
{
// ...
"scripts": {
"start": "nx run-many -t serve"
},
// ...
}
That way you can run npm run start
, which is easier to remember.
As app1
runs on a different port, we need to add a proxy.conf.json
inside apps/app2
, which routes requests to for example /config
from the Angular application to app1
. The proxy.conf.json
should look like this (replace 3333 with whatever port your app1
runs on):
// proxy.conf.json
{
"/config": {
"target": "http://localhost:3333",
"secure": false
}
}
We also have to tell Angular’s serve command to use this file by adding the following lines inside apps/app2/project.json
:
// apps/app2/project.json
{
// ...
"targets": {
// ...
"serve": {
// ...
"options": {
"proxyConfig": "apps/app2/proxy.conf.json"
},
// ...
},
// ...
},
// ...
}
This way every request going from app2
to /config
will be redirected to app1
while serving the applications locally.