Separate your routes

I prefer to add my routes in a separated file, it is easy to maintain. Also a prefix is a nice-to-have and required if you want to follow this tutorial. Create a routes.ts file.

routes.ts — only one route is declared for this tutorial

Create your paths in the controller

2 paths are defined the root path and our api/test path. The root path load a file in the response which contains the angular logic. The other path just returns a string.

In the root path @Res() response can be found. This is the same response as you know an express response. This can be used to transform the response to something else, to control it ourselves. In this case an html file will be loaded in the response.

In the testApi path @Res() response is not injected. If you do it here, the response will keep on loading if you try to access the input

All things will work, you think …?

We try to access the api/test endpoint …

it seems to work, our endpoint is accessable

We try to access the localhost:3001 endpoint, with some hope it will work …

yeah right, didn’t thought about this, angular load other files, also. Probably images and so will not load neither

We could add some middleware!

Middleware is a function, which is called before the router handler. So it will be handled before trying to access our controller our to look if our route exists. As provided in the image bellow, client side request a route → middleware intercept this and does something with it. Than it goes to the right route.

Middleware flow

This means we can use this to solve our problem. All calls needs to go through our frontend middleware, if it starts with /api it need to follow the way it follows normal. Else a file needs to be loaded into our route and return it to the route.

Frontend middleware flow

Create a frontend.middleware.ts file and add the following code. Adjust the allowedExt, as you need.

Register the middleware

After you created this file, it is not registered yet. The frontend middleware needs to be registered in the AppModule. It is registered for all routes and all request methods.

Try to go to http://localhost:3001

Everything works as expected

Working application can be found on: