Building the backend
In this lesson you will prepare the application backend an entry gate for communicating with persistance layer and hosting Angular application bundle.
Building the Backend#
Now implement the backend which will be used to host your Angular application on production. Add the necessary dependency to your Angular project:
npm i express
Create a new file called backend.ts in your project root directory (next to the package.json file) and add the following code to it:
import * as express from 'express';
import { join } from 'path';
export const app = express();
const distFolder = join(
process.cwd(),
'dist/my-universal-app'
);
app.get(
'*.*',
express.static(distFolder, {
maxAge: '1y',
})
);
app.use('/', express.static(distFolder));
app.use('/**', express.static(distFolder));
const port = process.env.PORT || 80;
app.listen(port, () => {
console.log(
`Backend is runing on: http://localhost:${port}`
);
});
The code above serves the business logic from api.ts under the /api/* endpoints (you will add it soon).
The code above serves all traffic with static files available in the dist folder where your Angular application will reside.
Compiler and package.json scripts#
The final step is to set up compiler options for the backend. Create a new file called tsconfig.backend.json and add the following configuration to it:
{
"extends": "./tsconfig.app.json",
"compilerOptions": {
"outDir": "./dist/backend",
"module": "commonjs",
"types": [
"node"
]
},
"files": [
"backend.ts"
]
}
Last but not least, adjust the scripts
section in the package.json file by changing the start
script and adding the build:backend
script:
"scripts": {
"ng": "ng",
"start": "node dist/backend/backend.js",
"build": "ng build --prod && npm run build:backend",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"build:backend": "tsc --project tsconfig.backend.json"
},
Testing the backend#
Build and run the backend using the following commands:
npm run build
npm start
Navigate with your browser to http://localhost. You should see your Angular application skeleton:
