DEV Community

Faisal
Faisal

Posted on

Angular SSR Redirection issue

Hi,

We have requirement of changing our domain and need to redirect all old application to new Urls. We are currently implemented Angular SSR and implemented the redirection (303) logic in Server.ts file. The redirection works fine. However , we have ended up with big issue that even after redirection, the application continue to run in locally and calls the APIs, including sessions in Angular Client side App.

I am new to Angular and wonder how can address this issue?

Please find the code snippet of the implementation.

server.get('*', (req, res) => {
        const dateTime = new Date();
        const request = require('request');
        if (dateTime.getHours() === 3) {
            vanityUrlResponse = null;
        }
        if (!vanityUrlResponse) {
            // Need to make the URL generic
            request(vanityUrlService, function(error, response, body) {
                if (!error && response.statusCode == 200) {
                    vanityUrlResponse = JSON.parse(body);
                    redirectUrl(vanityUrlResponse, req, res);
                }
            });
        } else {
            redirectUrl(vanityUrlResponse, req, res);
        }
        if (req.path == '/sitemap') {
            //refresh sitemap on nav
            fetchSiteMap(siteMapConfig);
        }
        if (req.path.includes('.')) {
            res.send(200);
        } else {
            res.render(indexHtml, {
                req,
                providers: [
                    { provide: APP_BASE_HREF, useValue: req.baseUrl },
                    { provide: REQUEST, useValue: req },
                    { provide: RESPONSE, useValue: res },
                ],
            });
        }
    });

    return server;
}

function redirectUrl(vanityUrlResponse, req, res) {
    const redirectRule = vanityUrlResponse.find(obj => obj.sourceUri == req.path);
    if (redirectRule != null) {
        res.redirect(301, redirectRule.desination);
    }
}
Enter fullscreen mode Exit fullscreen mode

I will definitely appreciate your help on this regard.

Regards,
Faisal

Top comments (0)