NodeJS Express Host index.html File Then Route To Specific Spa Route with Params

I have an application that uses Angular 13 as the frontend and nodeJS with express for the backend. The backend servers the frontend files. I am working on adding subdomains into my application and although I somewhat got it to work, there are a couple issues I am running into that I can’t quite find the solution too.

I have got most of it done but the issue seems to be that when I send the index.html with the sendFile() function, I manage to get the url changed to the Auth/Auth url with the parameters, but the website does not work and I get the following errors:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
This page isn’t working "domain" redirected you too many times.

I recently introduced subdomains and my server.js is:

const swagger = express();
var app = express();
//apiRoutes.use(enforce.HTTPS());
app.use(express.static(path.join(__dirname, '/dist/App'), { dotfiles: 'allow' }));

allRoutes.use(bodyParser.json({limit: '50mb'}));
allRoutes.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
allRoutes.use(cors());

// use JWT auth to secure the api
if (process.env.NODE_ENV !== "production" || process.env.ENV === "dev") {
    swagger.use('/', swaggerUi.serve, swaggerUi.setup(swaggerFile, { swaggerOptions: { persistAuthorization: true }}));
    app.use('/swagger', swaggerUi.serve, swaggerUi.setup(swaggerFile, { swaggerOptions: { persistAuthorization: true }}));
}
allRoutes.use('/webhooks', require('./backend/webhooks/webhooks.controller'));
allRoutes.use(subdomain('webhooks', require('./backend/webhooks/webhooks.controller')));

allRoutes.use('*', jwt());
// allRoutes.use(subdomain('api',  jwt()));
// api routes
allRoutes.use('/api/users', require('./backend/users/users.controller'));

// global error handler
// start server
app.use(subdomain('swagger', swagger));
// app.use(subdomain('webhooks', require('./backend/webhooks/webhooks.controller')));
app.use('/swagger', swagger);
app.get(/^/(?!api).*/,async function(req,res) {
    let isNonExcludedUrl = !req.url.includes('swagger') && !req.subdomains.includes('swagger') &&!req.url.includes('webhooks') && !req.subdomains.includes('webhooks');
    console.log('subdomain ', req.subdomains);
    if(req.subdomains.includes('webhooks')) {
        console.log('in webhooks')
    } else if(req.subdomains.length > 0 && isNonExcludedUrl) {
        console.log('processing website subdomain ');
        await website.checkSubdomainForWebsite(req, res)
    } else if (isNonExcludedUrl) {  //&& !req.url.includes('webhooks')
        res.sendFile(path.join(__dirname + '/dist/App/index.html'));
    }
});
app.use('/', allRoutes);
allRoutes.use(errorHandler);
app.use(errorHandler);

const port = process.env.PORT ? (process.env.PORT) : 4000;
var server = http.createServer(options, app);

server.listen(port, () => {
    console.log("server starting on port : " + port)
});

The checkSubdomainForWebsite function is:


async function checkSubdomainForWebsite(req,res) {
    let orgIdent = req.subdomains[0];
   
    if (orgIdent) {
       let qrDevice = await getOrCreateWebsiteDevice(orgIdent);

        let websiteUrl =  `/Auth/Auth`;

        res.sendFile(path.join(__dirname+'/dist/DineNGo/index.html'));
        res.redirect(url.format({
            pathname: websiteUrl, // assuming that index.html lies on root route
            query: {
                "qr": encodeURIComponent(encrypt(orgIdent)),
                "website": true
            }
        }));
    }
}

The expected behavior is when the checkSubdomainForWebsite() function is called,, right after the res.sendFile() is called and the index.html is loaded, I want to route to a specific page of the Angular SPA with query params. The Angular specific component based url I want to navigate to is Auth/Auth.

Upon researching this, I found that both the res.sendFile() and res.redirect should not be used together and I am pretty sure that is what is causing the issue but I cannot find an alternate approach that works. What is the best way I can host the index.html file and route to a specific component in the angular frontend through routes. I have provided my service.js and other functions below. Please let me know if more information is needed and thanks for the help.

Nginx is the right choice to serve the web interface, while node.js is usually only used to serve the backend APIs. Nginx excels at serving static content such as HTML, CSS, JavaScript, and image files efficiently. Nginx can act as a reverse proxy server, forwarding client requests to backend servers, in your case node.js APIs.

1

Yes, redirecting and sending file cannot be used together. So, you could send the file and then proceed with AJAX/Angular.

You could try redirecting first with query string, but include some flag to the query string the handler will read on redirect, and by it know that now it needs to send the file (or maybe in memory variable, in combination with other checks), (this makes two requests, and wil trigger other middleware, and might cause too many redirects, so it would be better to handle it on frontend), for example:

add flag to qs:

"redirected": true

read it every time:

if(req.query.redirected) return res.sendFile(path.join(__dirname+'/dist/DineNGo/index.html'));

code:

async function checkSubdomainForWebsite(req,res) {

    let orgIdent = req.subdomains[0];

    // add some flag to make sure it's redirect in combination with other checks
    if(req.query.redirected) return res.sendFile(path.join(__dirname+'/dist/DineNGo/index.html'));
   
    if (orgIdent) {
       let qrDevice = await getOrCreateWebsiteDevice(orgIdent);

        let websiteUrl =  `/Auth/Auth`;
        // redirect first
        res.redirect(url.format({
            pathname: websiteUrl, // assuming that index.html lies on root route
            query: {
                "qr": encodeURIComponent(encrypt(orgIdent)),
                "website": true,
                "redirected": true
            }
        }));
    }
}

As you know, a request-response cycle can have only one request and one response. Therefore res.sendFile and a subsequent res.redirect in the same cycle is a violation and it will throw the reported error.

The following is a workaround.

A minimal code below addresses the same by JavaScript in Browser. But it has an issue as well. This kind of code breaks back button. I still to find a solution to this particular issue – back button breaks. When user presses back button, it will not take to the page index.html.. If someone finds a fix for this issue, this could be one of the workarounds to this question.

server.js

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res
    .cookie('somecookie', 'somevalue')
    .sendFile(__dirname + '/' + './index.html');
});

app.get('/route1', (req, res) => {
  console.log(req.query);
  res.send('route1 navigation automated from the root route');
});

app.listen(3000, console.log('L@3000'));

index.html

<!DOCTYPE html>
<html>
  <head>
    Navigation automated to another route on load.
  </head>
  <body>
    <br />
    <br />
    <a href="./route1">A test route</a>
  </body>
  <script async>
    history.pushState({}, '', window.location.href);
    //for testing, assumed there is no other cookies
    const cookie = document.cookie;
    window.location.href = './route1?' + cookie;
    // to avoid unnecessary redirection, this cookie 
    // needs to be deleted once the redirection is done
    // { code to delete the cookie }
  </script>
</html>

Test results:

URL : http://localhost:3000
Redirected with the URL : http://localhost:3000/route1?somecookie=somevalue

server console : 
{ somecookie: 'somevalue' }

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật