To enable Server-Side Rendering (SSR) in an Angular application using Angular Universal, you need to add the Universal engine to your existing Angular project.
Here’s a step-by-step guide:
- Install Angular Universal
Run this command in your Angular project root:
ng add @nguniversal/express-engine
This will:
- Add necessary dependencies (
@nguniversal/express-engine
, @angular/platform-server
)
- Create a server-side entry point (
server.ts
)
- Create the
main.server.ts
file
- Add a
tsconfig.server.json
- Update
angular.json
with new SSR-related targets
- Add SSR scripts in your
package.json
- Verify Files
After running the command, you should see:
server.ts
– the entry point for the Express server
main.server.ts
– server-side version of the main app
- SSR configuration in
angular.json
- Build and Serve SSR
Now you can use the scripts in package.json
.
What These Commands Do
"dev:ssr": "ng run my_course:serve-ssr",
"serve:ssr": "node dist/my_course/server/main.js",
"build:ssr": "ng build && ng run my_course:server",
"prerender": "ng run my_course:prerender"
"dev:ssr"
ng run my_course:serve-ssr
- Runs the SSR server in development mode using Angular CLI.
- Good for debugging with live-reload support.
"serve:ssr"
node dist/my_course/server/main.js
- Serves the production build of the SSR app using Node.js directly.
- Use this when deploying to production.
️ "build:ssr"
ng build && ng run my_course:server
ng build
: Builds your Angular app for the browser (client).
ng run my_course:server
: Builds the server-side code using the server config.
"prerender"
ng run my_course:prerender
- Generates static HTML pages for your routes.
- Useful for SEO and performance if your content is mostly static.
- Only works if routes are known at build time (not dynamic).
✅ Summary
To enable SSR:
- Run
ng add @nguniversal/express-engine
- Use
build:ssr
to compile, and serve:ssr
to run your app
- Use
prerender
if you want static HTML output instead of dynamic SSR
Explore My Tech Universe
From in-depth tutorials to real-world development services — I build, teach, and share everything about modern web technologies.
Socials & Content:
Platforms & Writing:
Code & Projects:
Services & Training: