Skip to content

Commit

Permalink
chore(angular): add ssr
Browse files Browse the repository at this point in the history
  • Loading branch information
Muhammad Ahsan Ayaz committed Dec 8, 2024
1 parent 483af46 commit a9f1eac
Show file tree
Hide file tree
Showing 12 changed files with 117 additions and 61 deletions.
2 changes: 1 addition & 1 deletion angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
"server": "projects/demo/src/main.server.ts",
"prerender": true,
"ssr": {
"entry": "projects/demo/server.ts"
"entry": "projects/demo/src/server.ts"
}
},
"configurations": {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,4 @@
"@angular/common": "$@angular/common"
}
}
}
}
5 changes: 4 additions & 1 deletion projects/demo/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { Component, VERSION } from '@angular/core';
import { DeviceDetectorService } from 'ngx-device-detector';
import { NgClass, NgIf, NgFor } from '@angular/common';
import { KeysPipe } from './pipes/keys.pipe';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
standalone: false
imports: [NgClass, NgIf, NgFor, KeysPipe],
standalone: true
})
export class AppComponent {
propsToShow = ['userAgent', 'os', 'browser', 'device', 'os_version', 'browser_version', 'deviceType', 'orientation'];
Expand Down
11 changes: 11 additions & 0 deletions projects/demo/src/app/app.config.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';

const serverConfig: ApplicationConfig = {
providers: [
provideServerRendering()
]
};

export const config = mergeApplicationConfig(appConfig, serverConfig);
9 changes: 9 additions & 0 deletions projects/demo/src/app/app.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import {
ApplicationConfig,
} from '@angular/core';

export const appConfig: ApplicationConfig = {
providers: [

],
};
18 changes: 0 additions & 18 deletions projects/demo/src/app/app.module.ts

This file was deleted.

5 changes: 1 addition & 4 deletions projects/demo/src/app/pipes/keys.pipe.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'keys',
standalone: false
})
@Pipe({ name: 'keys', standalone:true })
export class KeysPipe implements PipeTransform {
transform(value, props: string[] = []): any {
const keys = [];
Expand Down
32 changes: 0 additions & 32 deletions projects/demo/src/app/server.ts

This file was deleted.

7 changes: 7 additions & 0 deletions projects/demo/src/main.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { config } from './app/app.config.server';

const bootstrap = () => bootstrapApplication(AppComponent, config);

export default bootstrap;
19 changes: 16 additions & 3 deletions projects/demo/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';

import { APP_ID, importProvidersFrom } from '@angular/core';
import { provideNoopAnimations } from '@angular/platform-browser/animations';
import { CommonModule } from '@angular/common';
import { AppComponent } from './app/app.component';
import { bootstrapApplication } from '@angular/platform-browser';

document.addEventListener('DOMContentLoaded', () => {
platformBrowserDynamic()
.bootstrapModule(AppModule)
bootstrapApplication(AppComponent, {
providers: [
importProvidersFrom(CommonModule),
{
provide: APP_ID,
useValue: 'serverApp'
},
provideNoopAnimations(),
]
})
.catch(err => console.error(err));
});
65 changes: 65 additions & 0 deletions projects/demo/src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine, isMainModule } from '@angular/ssr/node';
import express from 'express';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import bootstrap from './main.server';

const serverDistFolder = dirname(fileURLToPath(import.meta.url));
const browserDistFolder = resolve(serverDistFolder, '../browser');
const indexHtml = join(serverDistFolder, 'index.server.html');

const app = express();
const commonEngine = new CommonEngine();

/**
* Example Express Rest API endpoints can be defined here.
* Uncomment and define endpoints as necessary.
*
* Example:
* ```ts
* app.get('/api/**', (req, res) => {
* // Handle API request
* });
* ```
*/

/**
* Serve static files from /browser
*/
app.get(
'**',
express.static(browserDistFolder, {
maxAge: '1y',
index: 'index.html'
}),
);

/**
* Handle all other requests by rendering the Angular application.
*/
app.get('**', (req, res, next) => {
const { protocol, originalUrl, baseUrl, headers } = req;

commonEngine
.render({
bootstrap,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: browserDistFolder,
providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});

/**
* Start the server if this module is the main entry point.
* The server listens on the port defined by the `PORT` environment variable, or defaults to 4000.
*/
if (isMainModule(import.meta.url)) {
const port = process.env['PORT'] || 4000;
app.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
3 changes: 2 additions & 1 deletion projects/demo/tsconfig.app.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"src/main.ts",
"src/polyfills.ts",
"src/demo.ts",
"server.ts"
"server.ts",
"src/server.ts"
],
"include": ["src/**/*.d.ts"]
}

0 comments on commit a9f1eac

Please sign in to comment.