How to switch between Angular SSR and CSR based on detecting user-agent

An easy way to have Dynamic SSR

Since SSR is good for SEO and crawler bots, it's not good enough for users. For example, the transitions between pages could be slowed down if your site traffics get high. there are a lot of pros and cons for SSR and CSR I'm not digging into them. What we want here is to have both of them at the same time. We want SSR for SEO and CSR for users.

How

We are going to create an SSR Angular app and enable user-agent detection step by step. Let's Go!

Create a brand new Angular App

Run the CLI command ng new my-app to create a new angular project.

image.png

Install Angular SSR

Change the directory to my-app and run ng add @nguniversal/express-engine

image.png

Install the isbot package

In the terminal, run the command npm install isbot

image.png

Config server.ts

In the server.ts we are going to use isbot to detect whether the user-agent is a bot or not. To do that, we are going to import the package

import isbot from 'isbot';

Notice that the isbot is imported as a default import and it's not allowed by default.

image.png

To allow default import, we set "allowSyntheticDefaultImports": true, in tsconfig.json to allow default import.

image.png

After fixing the default import, now it's time to do the magic. We now detect bots and run the application as SSR otherwise, run the application as CSR.

// All regular routes use the Universal engine
  server.get('*', (req, res) => {
    if (isbot(req.headers['user-agent'])) {
      console.log('bot and running on SSR');
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
    } else {
      console.log('Running on CSR');
      res.sendFile(join(distFolder, `index.html`));
    }
  });

image.png

Test

To test how it works, we build and run the application on SSR and do some checks in the browser.

By clicking on localhost:4200 we will see the message in the console log that it's running on CSR.

image.png

Now, we check what will happen when the bot is coming to the site. To do that, we open network conditions in Inspect Element > Newrok > Network Conditions.

image.png

Select the Googlebot and reload the page.

image.png to check it by view on the source we to open it and again check it with the default user agent and the Googlebot

With the default user agent, we will see our application run on CSR.

image.png

And with the user-agent as the Googlebot, we will see the application in SSR.

image.png

image.png

Conclusion

With this approach, you can serve your heavy application SEO-friendly and User-friendly at the same time.

Please check out the source code at github.com/adnanebrahimi/angular-csr-ssr and don't forget to leave a comment if you like it.

Thanks for reading.