0

Angular Devs! I'm developing an Angular app where a lot of routes need to be rendered from the server-side which is called Angular Universal (SSR) in angular. But, in my application, there are a lot of private routes and feature modules that don't actually need to be rendered from the server. It would be okay if they render on the client-side. those are actually private routes like user profile, user profile edit modules.

What is the way to protect those route from rendering from the server. Or what is the way to make a route only to be render in client side?

2
  • 1
    Maybe this: stackoverflow.com/questions/52117185/… Commented Oct 10, 2021 at 17:10
  • Yeah, this one can protect routes with prefixes like /app/*. But it would be great if I can specify the route object. Commented Oct 10, 2021 at 18:01

1 Answer 1

2

This answer is from eneajaho from reddit.

Hi, I ran into your use-case some months ago, and I "found" a solution, and also opened an issue in the angular repo, in order to add the solution in the docs, but no success. Anyway, here is the issue: https://github.com/angular/angular/issues/41187

The solution: You should edit the server.ts file where the routing on the server side happens, and add an array of routes that you want to not render on the server side. Example:

const EXCLUDED_ROUTES: string[] = [
  '/test',
  '/auth(/)?*',
  '/back(/)?*',
];

Then, you should add a get with the excluded routes in the file, before the one that the server renders the app. And this route would directly return the index.html file, so it won't render it, but it will serve it as a static file, just like client-side rendering.

server.get(EXCLUDED_ROUTES, (req, res) => {
  res.sendFile(join(distFolder, 'index.html'));
});

The whole code:

/**
 * EXCLUDED_ROUTES contains all the paths that we don't want to render on the server
 *  Examples:
 *    '/test'
 *    '/back(/)?*' // regex: string starts with /back, '/' is optional, '*' it can be anything
 */
const EXCLUDED_ROUTES: string[] = [
  '/test',
  '/auth(/)?*',
  '/back(/)?*',
];

/**
 * Is used to exclude the routes from rendering on the server. Ex. Auth Page, Admin Page
 * To add or remove excluded routes modify the EXCLUDED_ROUTES array
 */
server.get(EXCLUDED_ROUTES, (req, res) => {
  res.sendFile(join(distFolder, 'index.html'));
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.