An Introduction To API Gateway in NestJS With Microservices and Rest APIs - Part 01 - by Marcos Henrique Da Silva - Medium
An Introduction To API Gateway in NestJS With Microservices and Rest APIs - Part 01 - by Marcos Henrique Da Silva - Medium
Photo by Mo Eid: https://www.pexels.com/photo/person-in-black-shirt-walking-on-sand-8347501/
Hello and welcome! In this article we are going to talk about API Gateway, microservices,
REST APIs (again) and all with NestJS
I was a bit reluctant to write about this topic, specially because when talking about API
Gateway and Microservices a lot of people deviates on how you should architect “in the
correct way” but still there are no much content about it using NestJS as well as NestJS
documentation for who is not used to Microservices might be complicated.
That said, my disclaimer here is that… Don’t take what I am writing today as set on stone
but… think that is one approach that might fit your needs and please feel free to
change/adapt/evolve what I am writing here for your personal needs.
Before we start…
This article might be slightly more advanced for who never worked with NestJS. If you are
new to NestJS and REST APIs I would recommend to read my previous article first:
Or, if you would like to check about GraphQL, you can go here:
Last, but not least… there’s also a very nice article about Kafka, microservices and NestJS
here:
That said, basic concepts you might need to follow up this article are:
NestJS basics (Should be nice to know the basics of building a REST API)
In this part 01 we are going to scaffold the project, create 2 isolated REST APIs and
configure the API Gateway to proxy those 2 isolated REST APIs
users: basic CRUD operation which will have their own REST API
tasks: a beginning of what could be a task manager which also will have their own REST
API
For authentication and to maintain things isolated, I will implement the authentication on
the API Gateway level, which for creating an JWT it will communicate with the users
microservice.
To make it easy to follow as a source code for future study, we are also going to use all those
projects in a monorepo with nx
Disclaimer: in this approach the microservices are exposing their own REST endpoints
but keep in mind that following this approach then you should care about not exposing
their endpoints in a public way. This is easily manageable with Kubernetes and/or any
Cloud infra like AWS, Azure
It will ask for an application name that in our case is the main one and we are calling it api-
gateway
creating a project with nx
NX is a build system that allows monorepo approach. For this project we are not going
deeper on this but just organising all the projects in one single repo that I can share in the
end of the article ;)
The result is a project with apps/api-gateway which is your desirable API Gateway that we
are going to code on. The default port is 3333.
To test is everything is ok just run npm start in your terminal. You should be able to get the
classic “Hello world” in your root directory.
Now to have the API Gateway working, we still need to have the other microservices in
place. Let’s scaffold them with:
nx g @nrwl/nest:app users
and
nx g @nrwl/nest:app tasks
Once they are done, we will have all the 3 scaffolded projects:
In order to run all the projects at the same time, I am creating a .env file to each project
containing the PORT value with the following: 3331, 3332, 3333
in api-gateway:
PORT=3330
in users
PORT=3331
in tasks
PORT=3332
With that made… we can finally run the all the three applications at the same time with just
one command:
nx run-many --target=serve
- api-gateway
- tasks
- users
—————————————————————————————————————————————————————————————————————————
—————————————————————————————————————————————————————————————————————————
————————————————————————————————————————————————————————
In the users project we are going to scaffold the users module with:
A problem on NX and Nest CLI is that now you still need to import the Users/Tasks in their
respectives app.module.ts, as well as installing the following dependency:
npm i @nestjs/mapped-types
Now we are good to test like a curl to http://localhost:3331/api/users
How do we connect this to the API Gateway now? The short answer is: http-proxy-
middleware
npm i http-proxy-middleware
Now, in the main.ts from api-gateway we will import the proxy middleware
// Proxy endpoints
app.use('/api/users', createProxyMiddleware({
target: USERS_SERVICE_URL,
changeOrigin: true,
}));
app.use('/api/tasks', createProxyMiddleware({
target: TASKS_SERVICE_URL,
changeOrigin: true,
}));
await app.listen(port);
Logger.log(
` 🚀Application is running on:
http://localhost:${port}/${globalPrefix}`
);
}
bootstrap();
With that you will have the API Gateway up and running and every time you will hit the
/api/users* or /api/tasks* the correct REST microservice will be proxied properly
Handling Auth
For handling Auth with the http-proxy-middleware we can use their built-in built-in
function onProxyReq:
app.use('/api/users', createProxyMiddleware({
target: USERS_SERVICE_URL,
changeOrigin: true,
onProxyReq: (clientRequest, req) =>{
//some validation goes here
}
}));
Keep in mind that the request will be proxied to the next “server” that most possibly won’t
be in the same local instance.
If you are using JWT and the header Authorisation with Bearer JWT then you could have a
service in the API Gateway that confirms that the JWT is valid and then move forward, else
finishing the request/response cycle right away.
By now we scaffolded the monorepo project with NX, created the basics of the API Gateway,
scaffolded 2 REST APIs and slightly tackled the how to manipulate the Authorisation flow.
In the next article we are going to configure the microservice module for users and tasks as
well as finishing some CRUD operations to have a useful project as a guideline. Later on we
are going to actually implement the Auth flow, including permissions.
You can check the full source code for this project in this public branch on Github
If this article was anyhow useful please follow me for more content, give a clap and/or a
comment. That makes me happy to write more ;)
If this kind of article is too simple and you feel yourself prepared to a real adventure,
specially on a remote good paid basis, please try to join Toptal with my
referral link https://topt.al/KncQD8. Toptal is a great community for freelancers and I
will be happy to see you there!