Loading preferred routes in Angular 6+ Universal for faster performance

In my Angular 7 application, I have Angular Universal set up with Express and I am also utilizing Angular Routing. My goal is to have only the pre-login routes (marketing views) rendered server-side, while post-login routes are loaded using traditional client-side Angular loading.

Currently, I have successfully implemented this setup for routes navigated using router.navigate or [routerLink]. However, when a user refreshes the page in the browser, issues arise due to browser dependencies like cookies and local storage on certain routes.

The desired functionality is for routes excluded from server-side rendering to load as if Angular Universal is not present when directly navigated to or refreshed. Routes designated for server-side rendering should render on the server.

In my server.ts file, I have the following line that uses Angular Universal for all routes:

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

I have attempted to specify the routes I want to use Universal for, but this approach results in a 404 error for all other routes. I believe I may be approaching this issue incorrectly.

Answer №1

If you want to achieve this functionality, you can utilize express routing rules to make it happen.

To implement this, you need to modify your middleware responsible for server-side rendering to verify the "allowed" ssr routes and then add a catch-all rule after it. Below is an example of what this might look like:

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The absence of typings.json in Typescript is creating an issue

As of now, I am encountering the following error during compilation: typings.json is missing In my existing packages.json, I have included the following dependency: "devDependencies": { "typescript": "^2.6.1", ... } Do you have any suggestion ...

What is the best way to access a post request value from one JavaScript file to another in a Node.js environment

Hey there, longtime listener, first-time caller. I'm diving into the world of node JS, Javascript, and express but I've hit a roadblock that's been giving me a headache for three days now. Hoping someone here can lend a hand. I have a &apos ...

Encountering a 'blocked:other' error status while making a REST API call in my Angular application to retrieve data from the server

Example of the requested REST API URL: http://example.com/controller/api?bannerId=1&value=23 Encountering a browser error status: blocked:other while attempting to make an HTTP request to the server from the Angular application. ...

Using JSDoc with "T extending Component"

get_matching_components<T extends Component>(component_type_to_return: { new (doodad: Doodad): T }): T[] { return this.components.filter(component => component instanceof component_type_to_return) } In TypeScript, I created a method to retrie ...

New post: "Exploring the latest features in Angular

Looking for help with integrating Angular and SpringREST to fetch data from the backend? Here's my situation: I need to retrieve a JSON string from the backend using a POST request, send it to my site's hosted link, and display it on the user int ...

Using object bracket notation in TypeScript to retrieve values from props with the help of string interpolation

I encountered an issue in my code while attempting to utilize a variable within my TSX component. This problem arises due to the dynamic props being passed into the component, which are always a string that matches one of four keys in the "characters" obje ...

An Unexpected ER_BAD_FIELD_ERROR in Loopback 4

I encountered an unusual error: Unhandled error in GET /managers: 500 Error: ER_BAD_FIELD_ERROR: Unknown column 'role_id' in 'field list' at Query.Sequence._packetToError (/Users/xxxx/node_modules/mysql/lib/protocol/se ...

Encountering a PropertyTypeError while attempting to process a payment via Stripe in conjunction with use-shopping-cart on Next.js

Upon reaching the checkout page, I encounter the message: Invalid value with type "undefined" was received for stripe. Valid type for stripe is "string". This issue seems to be related to the redirectToCheckout function. Can someone assist me? The cart-s ...

Utilizing custom types in React with TypeScript and Prop-Types

Currently, I am working with a string type literal that looks like this: type MyType = 'str1' | 'str2' | 'str3'. I need one of my props to only accept this specific type, but I'm struggling to specify this in PropTypes. ...

Merge rxjs streams, identify modifications, and yield a single result

In the context of using Angular with .net Core WebApi, let's consider the development of a time management application designed to monitor task durations. The user initiates a task on the front end which triggers a timer displaying elapsed time. The ...

Looking for solutions to resolve the "connect() failed (111: Connection refused)" error while attempting to restart a Node.js server?

Situation: I have a setup using Nginx and NodeJS to power my website. The server sees around 300 concurrent users at any given time, browsing various pages. I rely on the pm2 tool to manage my node applications. Challenge: However, whenever I restart th ...

Techniques for returning errors to the calling function using async functions

I am currently encountering an error where if "dateofBirth" is not found, an empty object is sent back to the client. How can I change this so that an error object is sent back instead of an empty object? Essentially, I want to send back a catch process. ...

Using a REST API to make a POST request that calls a function and passes

Within my index.js file, the following code is implemented: app.post("/token", function (req, res) { var token = req.body createToken(token); }); This functionality is then exported by token.js const createToken = (token) = (req, res) => ...

Structuring Server Side Code with Node.js and Express

I am faced with the task of restructuring my server and its components. My goal is to streamline the process by segregating different functionalities. app.post("/login", function(request, response) { }); app.post("/register", function(request, response) ...

Streamline Jasmine-Node and express.js with automated processes

After creating a basic Webapp using express.js, testing it with jasmine-node has been smooth. However, I find myself manually starting the server before each test, which is becoming cumbersome. I am looking for guidance on setting up a spec-helper that ca ...

I am trying to figure out how to retrieve the name of the property that is bound to [(ngModel)] in Angular 6

Here is a custom component example: <form-text [(ngModel)]="dataItem.prop1"> </form-text> Is there a way to extract the property name "prop1" from the class in this scenario? @Component({ selector: 'form-text', template ...

Issue with rendering an object's property using EJS

Trying to include the author's username in reviews within an ejs template for my app. The following code snippet: <%= review.author %> is functioning correctly and displays: { _id: 5eff6793e7f26811e848ceb1, username: 'mike', __v: 0 ...

What is the relevance of `type Constructor<T> = Function & { prototype: T }` in relation to Abstract constructor types in TypeScript?

Can anyone help me understand how to use the Abstract constructor types in TypeScript? I came across this question and answer on Stack Overflow regarding the topic: Abstract constructor type in TypeScript The accepted answer provided a one-liner code sni ...

Angular6 Observables used in API service with dynamic arguments

In order to achieve the desired behavior, I am trying to implement a system where when a user selects a label from a dropdown menu, an API call is made with that specific label as an argument. Subsequently, a chart should be redrawn using the data received ...

Tips for acquiring the newest router in an angular environment

Is there a way to retrieve and store the URL of the latest router that the user has visited in local storage? Any suggestions would be greatly appreciated. Thank you! ...