- Building an API Gateway using Node.js
- Originally written by Peter Marton
- The Nuggets translation Project
- Permanent link to this article: github.com/xitu/gold-m…
- Translator: MuYunyun
- Proofread by: Jasonxia23, CACppuccino
When an external client accesses a service in a microservice architecture, the server has some common requirements for authentication and transport. The API gateway provides a sharing layer to handle differences between service protocols and meet the requirements of specific clients, such as desktop browsers, mobile devices, and older systems.
To ensure real-time and accurate content, you can follow personal blogs
Microservices and consumers
Microservices are service-oriented architectures that allow teams to design, develop, and publish applications independently. It allows for technical diversity at all levels of the system, where teams can benefit from using the best language, database, protocol, and transport layers for a given technical challenge. For example, one team can use JSON over HTTP REST, while another team can use a message broker such as gRPC or RabbitMQ over HTTP/2.
Using different data serializations and protocols may be powerful in some cases, but customers who want to use our products may have different needs. This problem can also occur in systems with a homogeneous technology stack, as customers can move from desktop browsers to legacy systems via mobile devices and game consoles. One customer might want XML, while another might want JSON. In many cases, you need to support both.
Another challenge you can face when customers want to use your microservices comes from common shared logic (such as authentication), because you don’t want to re-implement the same things across all your services.
Summary: We don’t want to implement our internal services in our microservices architecture to support multiple clients and reuse the same logic. This is where THE API gateway comes in, as a shared layer to handle differences between service protocols and meet specific client requirements.
What is an API gateway?
An API gateway is a service in a microservices architecture that provides a shared layer and API for clients to communicate with internal services. API gateways can route requests, transform protocols, aggregate data, and implement shared logic, such as authentication and rate limiters.
You can think of API gateways as entry points to our microservices world.
Our system can have one or more API gateways, depending on the customer’s requirements. For example, we can provide separate gateways for desktop browsers, mobile applications, and public apis.
API gateways serve as entry points for microservices
Node.js is the API gateway for the front-end team
Because the API gateway provides functionality to client applications such as browsers, it can be implemented and managed by the team responsible for developing front-end applications.
This also means that it is up to the team responsible for a particular customer to choose which language to implement the API Gateway in. Because JavaScript is the primary language for developing browser applications, Node.js can be an excellent choice for implementing API gateways even if your microservices architecture is developed in a different language.
Netflix successfully uses The Node.js API gateway and its Java back end to support a wide range of clients – to learn more about their approaches read The “Paved Road” PaaS for Microservices at Netflix
The way Netflix handles different clients,resources
API Gateway Function
As we discussed earlier, you can put common shared logic into your API gateway, and this section covers the most common gateway responsibilities.
Routing and version control
We define the API gateway as the entry point for your microservices. In your gateway service, you can specify routing requests from clients to specific services. You can even process versioning or change the back-end interface through routing, while the exposed interface stays the same. You can also define new endpoints that work with multiple services in your API gateway.
API gateways serve as microservices entry points
Upgrade of gateway design
The API gateway approach can also help you decompose your overall application. In most cases, refactoring a system on the microserver side is neither a good idea nor possible because we need to deliver new and existing functionality to the business during refactoring.
In this case, we can put the proxy or API gateway ahead of our overall application, implement the new functionality as a microservice, and route the new endpoint to the new service while serving the old endpoint through the old route. In the future, we can also break down the whole thing by converting existing functions into new services.
As the gateway design is upgraded, we can achieve a smooth transition from the overall architecture to micro-services
Upgrade of API gateway design
certification
Most microservices infrastructures require authentication. Adding shared logic, such as authentication, to the API gateway helps you keep your services small and manage domains centrally.
In a microservice architecture, you can protect your services in a DMZ (protected zone) through network configuration and expose them to customers through an API gateway. The gateway can also handle multiple authentication methods. For example, you can support both cookie – and token-based authentication.
API gateway with authentication function
Data aggregation
In microservices architectures, there may be different levels of aggregation of data required by clients, such as for the non-normalized data entities generated in various microservices. In this case, we can use our API gateway to resolve these dependencies and collect data from multiple services.
In the figure below, you can see how the API gateway returns user and credit information as a piece of data to the client. Note that this data is owned and managed by different microservices.
Serialization format conversion
We need to support different data serialization formats on the client side.
Imagine our microservices using JSON, but our customers can only use XML APIs. In this case, we can convert JSON to XML in the API gateway rather than implementing it separately across all microservers.
Protocol conversion
Microservices architecture allows multi-channel protocol transport to take advantage of multiple technologies. However, most clients support only one protocol. In this case, we need to switch the client’s service protocol.
The API gateway can also handle protocol translation between clients and microservers.
In the next image, you can see all the communication the client wants to do over HTTP REST, while the internal microservice uses gRPC and GraphQL.
Rate limiting and caching
In the previous example, you saw that we could put common shared logic, such as authentication, in the API gateway. In addition to authentication, you can also implement rate limiting, caching, and various reliability features in the API gateway.
Overloaded API gateways
When implementing your API gateway, you should avoid putting non-generic logic, such as specific data transformations, into your gateway.
Services should always have full ownership of their data domains. Building an overburdened API gateway and letting the microservices team control it goes against the idea of microservices.
This is why you should be concerned about data aggregation in your API gateway – you should avoid it having a lot of logic that can even contain specific data transformation or rule processing logic.
Always define clear responsibilities for your API gateway and include only the common shared logic within it.
Node. Js API gateway
When you want to perform simple operations within an API gateway, such as routing requests to specific services, you can use a reverse proxy like Nginx. At some point, however, you may need to implement logic that is not supported by the general proxy. In this case, you can implement your own API gateway in Node.js.
In Node.js, you can simply broker requests for specific services using the HTTP-Proxy package, or you can create API gateways using the more feature-rich Express-Gateway.
In our first API gateway example, we validated the request before delegating code to the User service.
const express = require('express')
const httpProxy = require('express-http-proxy')
const app = express()
const userServiceProxy = httpProxy('https://user-service')
// Identity authentication
app.use((req, res, next) = > {
// TODO:Authentication logic
next()
})
// Proxy request
app.get('/users/:userId', (req, res, next) => {
userServiceProxy(req, res, next)
})
Copy the code
Another example might be to make a new request in your API gateway and send the response back to the client:
const express = require('express')
const request = require('request-promise-native')
const app = express()
// GET /users/me
app.get('/users/me'.async (req, res) => {
const userId = req.session.userId
const uri = `https://user-service/users/${userId}`
const user = await request(uri)
res.json(user)
})
Copy the code
Node.js API gateway summary
The API gateway provides a shared layer to meet customer needs through the microservices architecture. It helps keep your service small and focused. You can put different generic logic into your API gateway, but you should avoid overuse of the API gateway, because much of the logic can be controlled from the service team.
The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, React, front-end, back-end, product, design and other fields. If you want to see more high-quality translation, please continue to pay attention to the Project, official Weibo, Zhihu column.