12

I was playing with angular universal a bit but cant find option to use server side rendering only for some pages like home page and render all other routes in standard angular way. I don't want to use server side rendering for private pages where SEO is not needed. I can configure routes in express like this

// send all requests to Angular Universal
// if you want Express to handle certain routes (ex. for an API) make sure you adjust this
app.get('/', ngApp);
app.get('/home', ngApp);
app.get('/about', ngApp);

Ideally I don't want to know about NodeJs at all and configure it on angular routes config with property like serverSide: true

const appRoutes: Routes = [
  //public route, I want server rendering for SEO
  { path: 'home', component: HomeComponent, serverSide: true },
  //private user profile page, SEO is not needed
  { path: 'user/profile/:id', component: UserProfileComponent },
];
Andzej Maciusovic
  • 4,306
  • 1
  • 29
  • 40

1 Answers1

13

In your server.ts for routes you don't want to render just do as below

app.get('/api/**', (req, res) => { });

app.get('/app/**', (req, res) => {
  console.log('not rendering  app pages');
});

app.get('/auth/**', (req, res) => {
  console.log('not rendering auth page');
});

// All regular routes use the Universal engine

app.get('*', (req, res) => {
  res.render('index', { req });
});

Hope this helps.

Blugene
  • 131
  • 2
  • 3
  • 5
    You will need to return the index.html file for the non rendered routes, using something like: `app.get(routePattern, (req, res) => { res.sendFile(distFolder + '/index.html'); });` – Rafael Cerávolo Jun 20 '20 at 20:35
  • is it possible to combine `/app/**` and `/auth/**` in same line instead of two different code ? – Santosh Dec 17 '21 at 11:29
  • 2
    @Santosh You could use regular expressions to combine /app/** and /auth/** `app.get(/^\/(app | auth)\/(.+)/, function (req, res, next) {}` – Wahrenheit Sucher Mar 31 '22 at 20:46