Angular 6+ Universal only preload specific routes

Viewed 1590

I have an Angular 7 application with Angular Universal setup(express). I am also using Angular Routing. I am trying to set it up to where only my pre login routes(marketing views) are rendered server side and anything post login is loaded through traditional angular client side loading.

I have it working if the user navigates the site using router.navigate or [routerLink], however if the user click the browser refresh it blows up because of browser dependencies for cookies and local storage on certain routes.

The desired outcome is if a user navigates directly or refreshes on a route that is excluded from SSR, it loads as if Angular Universal is not there. If a route that I designate SSR is navigated to it renders server side.

in my server.ts I have this line which uses Universal for all routes.

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

I tried specifying which routes I want to use universal, but then I get a 404 on all others. I am sure I am just going about this wrong.

1 Answers

You can do this with express routing rules.

Alter your middleware which does the server-side rendering to check for the "allowed" ssr routes, then add a catch-all after it. Might look something like this

// Server-Side Rendering catch call
app.get('*', (req, res, next) => {
    if (['/campaign', '/', '/any/other/page'].indexOf(req.originalUrl) < 0) {
        return next(); // continue path matching
    }
    renderModuleFactory(
       ... your existing SSR implementation
});

// Catch-all to return normal client-side rendered app
app.get('*', (req, res) => {
    return res.sendFile(path.join(APP_CONFIG.client_root, './index.html'));
});
Related