Skip to content

Angular SSR in firebase function

run your angular ssr server in firebase function

first you need to make sure ssr works:

npm run build:ssr && npm run server:ssr

In server.ts make server variable is global and export it.

export const server = app();
function run(): void {
const port = process.env.PORT || 4000;

// Start up the Node server
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}

then comment the line where the function run is called

if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
run();
}

becomes

// if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
// run();
// }

then init firebase project, in your angular app folder

firebase init

in firebase prompt: "Which firebase CLI features do you want to setup?" Choose ...

(*) Functions
(*) Hosting

copy the ssr build artifacts(dist), to firebase functions folder

cp -r dist functions/

In functions/src/index.ts replace the content with this:

import * as functions from 'firebase-functions';

const server = require(`${process.cwd()}/dist/server/main.js`).server;
export const ssr = functions.https.onRequest(server);

finally you need to setup proxy server, that points to that firebase function. the proxy is required for the app to work properly.