To enable Server-Side Rendering (SSR) in Angular, you use Angular Universal, which allows your app to be rendered on the server before being sent to the browser. This improves SEO, speeds up first contentful paint, and enhances social sharing capabilities.
Here’s a step-by-step guide:
π§ Step 1: Add Angular Universal to Your App
Use the Angular CLI to add SSR support:
This command does the following:
-
Installs required dependencies like
@nguniversal/express-engine
-
Adds server-specific files:
server.ts
,main.server.ts
,app.server.module.ts
-
Updates
angular.json
with server build configuration -
Configures a basic Express server
π Step 2: Understand the New File Structure
After running the command, you'll see:
-
src/main.server.ts
– entry point for server bundle -
src/app/app.server.module.ts
– your AppModule tailored for SSR -
server.ts
– Express server that handles SSR requests
π Step 3: Build the Application
To build both the browser and server versions of the app:
This builds:
-
dist/browser/
– client-side app -
dist/server/
– server-side app
π Step 4: Serve the SSR Application
After building, run the server with:
This uses the Express server to serve your Angular app with SSR.
⚙️ Step 5: Configure Deployment (Optional)
For production:
-
Host it on Node.js-compatible platforms (e.g., Firebase Functions, Vercel, AWS, etc.)
-
Optimize for caching, pre-rendering, or lazy-loading
π Benefits of Angular SSR
Benefit | Why It Matters |
---|---|
SEO | Crawlers can index rendered HTML |
Performance | Faster first paint and perceived speed |
Social Sharing | Meta tags are server-rendered |
If your site is mostly static, you can pre-render pages at build time:
This generates static HTML pages without needing a Node server.