I updated my Angular 8 project to Angular 9. I ran the command “npm run build: ssr && npm run serve: ssr”. It worked flawlessly and “browser” and “server” folders were created in the “dist” folder.
I uploaded these files to my server (Plesk panel). I set it to read server / main.js file with node.js.
It failed because it could not find “browser / index.html” in “dist” folder. I created a folder called “dist” and moved the “browser” folder into it.
Then it timed out, my project did not work. I run Node.js in development mode to see the error, but it says there is a timeout.
server.ts
import 'zone.js/dist/zone-node';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '@angular/common';
import { existsSync } from 'fs';
const domino = require('domino'); // kb
const fs = require('fs'); // kb
const template = fs.readFileSync('dist/browser/index.html').toString(); // kb
const win = domino.createWindow(template); // kb
global['window'] = win;
global['document'] = win.document;
global["branch"] = null;
global["object"] = win.object;
global['DOMTokenList'] = win.DOMTokenList;
global['Node'] = win.Node;
global['Text'] = win.Text;
global['HTMLElement'] = win.HTMLElement;
global['navigator'] = win.navigator;
// The Express app is exported so that it can be used by serverless Functions.
export function app() {
const server = express();
const distFolder = join(process.cwd(), 'dist/browser');
const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
server.engine('html', ngExpressEngine({
bootstrap: AppServerModule,
}));
server.set('view engine', 'html');
server.set('views', distFolder);
// Example Express Rest API endpoints
// app.get('/api/**', (req, res) => { });
// Serve static files from /browser
server.get('*.*', express.static(distFolder, {
maxAge: '1y'
}));
// All regular routes use the Universal engine
server.get('*', (req, res) => {
res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
});
return server;
}
function run() {
const port = process.env.PORT || 4000;
// Start up the Node server
const server = app();
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
run();
}
export * from './src/main.server';
main.server.ts
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
export { AppServerModule } from './app/app.server.module';
export {ngExpressEngine} from '@nguniversal/express-engine';
export { renderModule, renderModuleFactory } from '@angular/platform-server';
tsconfig.app.json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}
tsconfig.server.json
{
"extends": "./tsconfig.app.json",
"compilerOptions": {
"module": "commonjs",
"outDir": "./out-tsc/app-server",
"baseUrl": ".",
"types": [
"node"
]
},
"angularCompilerOptions": {
"entryModule": "./src/app/app.server.module#AppServerModule"
},
"files": [
"src/main.server.ts",
"server.ts"
]
}
tsconfig.json
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"module": "esnext",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2018",
"dom"
]
}
}
package.json
{
"name": "kodumunblogu",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"compile:server_bak": "webpack --config webpack.server.config.js --progress --colors",
"build:ssr_bak": "npm run build:client-and-server-bundles && npm run compile:server",
"serve:ssr_bak": "node dist/server",
"build:client-and-server-bundles_bak": "ng build --prod --aot && ng run kodumunblogu:server:production --bundleDependencies all",
"dev:ssr": "ng run kodumunblogu:serve-ssr",
"serve:ssr": "node dist/server/main.js",
"build:ssr": "ng build --prod && ng run kodumunblogu:server:production",
"prerender": "ng run kodumunblogu:prerender",
"postinstall": "ngcc"
},
"private": true,
"dependencies": {
"@angular/animations": "^9.0.0",
"@angular/cdk": "^9.0.0",
"@angular/common": "~9.0.0",
"@angular/compiler": "~9.0.0",
"@angular/core": "~9.0.0",
"@angular/forms": "~9.0.0",
"@angular/material": "^9.0.0",
"@angular/platform-browser": "~9.0.0",
"@angular/platform-browser-dynamic": "~9.0.0",
"@angular/platform-server": "^9.0.0",
"@angular/router": "~9.0.0",
"@fortawesome/angular-fontawesome": "^0.6.0",
"@fortawesome/fontawesome-svg-core": "^1.2.15",
"@fortawesome/free-brands-svg-icons": "^5.7.2",
"@fortawesome/free-solid-svg-icons": "^5.7.2",
"@fullcalendar/core": "^4.3.1",
"@nguniversal/express-engine": "^9.0.0",
"@ngx-share/button": "^7.1.2",
"@ngx-share/buttons": "^7.1.2",
"@ngx-share/core": "^7.1.2",
"bootstrap": "^4.3.1",
"chart.js": "^2.9.3",
"core-js": "^2.6.5",
"express": "^4.17.1",
"jquery": "^3.3.1",
"primeicons": "^2.0.0",
"primeng": "^9.0.0-rc.4",
"quill": "^1.3.6",
"rxjs": "~6.5.4",
"tslib": "^1.10.0",
"webpack-node-externals": "^1.7.2",
"zone.js": "~0.10.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.900.1",
"@angular/cli": "~9.0.1",
"@angular/compiler-cli": "~9.0.0",
"@angular/language-service": "~9.0.0",
"@nguniversal/builders": "^9.0.0",
"@types/express": "^4.17.0",
"@types/jasmine": "~3.3.10",
"@types/jasminewd2": "~2.0.3",
"@types/node": "^12.11.1",
"codelyzer": "^5.1.2",
"jasmine-core": "~3.3.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~4.0.1",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.5",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"protractor": "~5.4.0",
"ts-loader": "^4.0.0",
"ts-node": "~8.0.3",
"tslint": "~5.14.0",
"typescript": "~3.7.5",
"webpack-cli": "^3.1.0"
}
}
3
Answers
I doubt tsconfig.json file baseUrl is the issue. You may remove the same and try once in local then server.
These are the steps that I got Angular 9 with .net core 3.1 all working using Angular Universal and NodeIIS.
This can get you started https://medium.com/@MarkPieszak/angular-universal-server-side-rendering-deep-dive-dc442a6be7b7.
Note my final project is not pre-rendered it is ssr meaning certain pages have parameters and will keep growing over time so I can’t pre-render (cache) certain pages it needs to be ssr.
I created an angular app within VS .net core and added universal. Then after you can run ng serve make sure you can run the following on your angular 9 app.
Note make sure your code will work for ssr
Fix Angular JS code to work for SSR
(isPlatformBrowser(this.platformId)) { }
global[‘document’] and app.use(cors()); for server.ts as you will
need to set these up too.
Server stuff
look at the solution here for c# .net core for getting cors working https://www.codeproject.com/Questions/5162494/Currently-I-am-working-on-angular-and-web-API-NET
Follow steps above to remove — on both lines and I used published wizard straight to IIS from VS (it copies a folder in the root containing lots of Dlls etc, a ClientApp folder that contains dist and a node_modules) See publish does all the hard work for you. If your doing this manually you copy entire contents from debug…publish folder. I did not even have to mess around with the web.config file. Once it published and I setup domain to point to that folder in IIS.
install nodeiis and run npm run serve:ssr which will process all requests for website and translate to ssr – best to use pm2 (npm i pm2)
I added this to the VS net core SPA startup
When testing locally I can run ng serve and change localhost to 4200 and then when I run npm run serve:ssr I can change to 4000 and you can refresh you website and see how it renders differently
Notes
Here is my frontend code working shows how i setup resolve to make sure the content is loaded correctly for seo – Angular SSR Refresh/Load Page Pending Api Call
You may need to setup angular side cors too if you get preflight error – https://medium.com/@alexxsanya/fix-cors-in-angular-8-using-cli-proxy-configuration-787589f06f94
I wish they made it easier but after all these steps it works and the website loads instantly. When I look at the page title using view source its the index title but Google Webmasters has read the correct title on all pages.
Alternative Solution
There is a paid service called prerender.io I was going to use them costs about €9 a month and can implement easy https://github.com/dingyuliang/prerender-dotnet/wiki/Prerender-Middleware-for-ASP.NET-Core. I used it for an angularJS project and it works fine.
Hope these steps helps someone as it took me ages to get this working
-make sure in your "Document Root" to choose the browser folder not server.
-in your server.ts REMOVE this if condition:
and replace it with just:
then restart your node.js app again from the plesk GUI