NGINX, TypeScript, Angular, and NodeJS: Setting up Single Page Applications

2 Minute(s) to read


This blog post will go in-depth with setting up NGINX for serving and hosting a single page application that is likely developed with TypeScript and some kind of frontend framework such as Angular.

Read this blog post on how to setup a local web development environment for a TypeScript-driven web application.

Flow Diagram

The diagram below outlines how a single request is handled, depending on the endpoint that the request is made against.

Untitled Diagram

NGINX features the ability to distribute requests to a collection of configured endpoints that are specified in the configuration file. This is achieved through the usage of an upstream configuration, whereby a logical resource is defined and specifies multiple endpoints that a request can be redirected to. NGINX then makes use of "IP hashing" to ensure that all subsequent requests from a client or User Agent are sent to the same endpoint as their initial request. This is done for session management purposes, although the implementation of session management is entirely dependent on your server-sided implementation.

If you make use of a database store for session information, then it's unlikely that this would affect your configuration, as each instance of your RESTful API backend will reference the same data, providing that they are all configured to use the same database store. If your RESTful API backend makes use of an in-memory session store, then this will affect your configuration without IP hashing, as there is no immediate way for the multiple instances of your RESTful API backend to share session information about users between instances.

More information on upstream configurations for NGINX.

Find below an example configuration.

upstream backend {
    server api1.yourwebsitename.local:3031;
    server api2.yourwebsitename.local:3032;
    server api3.yourwebsitename.local:3033;

This logical resource is then referenced by a NGINX route when an incoming r request is served.

location /api {
	proxy_pass http://backend;
	proxy_http_version 1.1;
	proxy_set_header Upgrade $http_upgrade;
	proxy_set_header Connection 'upgrade';
	proxy_set_header Host $host;
	proxy_cache_bypass $http_upgrade;

Serving Pages

The benefit of using a combination of a NodeJS instance that uses the ExpressJS framework with NGINX, is that static files for the frontend can be loaded very fast, while server-sided operations can be offloaded to the RESTful API backend (NodeJS) where necessary. Additionally, NGINX can manage load balancing for incoming requests, ensuring that backend services don't crumble under the demand of users.

NGINX Configuration



Load Balancing