API Versioning with Node.JS

peng.yeng
3 min readSep 22, 2021

--

API versioning is one of the key concept when we consider API implementation. It’s useful when we need to maintain coexistence of multiple versions of the API implementation. It happens when you need to enhance the functionalities and at the same time support existing API consumer which still rely on the current implementation.

Typically, you do not need to maintain API versioning when the change can be gracefully handled by the application logic and the implementation won’t result to any breaking change. Breaking change refers to implementation which affects the request or response of your existing API. API consumer can no longer consume the API as the API integration contract has been changed.

Implementation of API versioning

There are many approaches can be used to handle API versioning. In generally, API service provider needs an indicator in API request to understand which version the API consumer need. I will cover two of the common approaches that you can use for your implementation; which are URL based versioning and Header based versioning. These 2 approaches have their pros and cons when they come to implementation. It depends on your requirement and which approach fit your needs.

URL based versioning

As the name suggested, URL based versioning includes the version in API request URL. You may see a URL like https://example.com/api/v1/helloworld. This is a straightforward approach for API versioning. API consumer can easily identify the version by looking at the URL. With the version number includes in URL will also make it easy if you need to cache the API response.

URL based versioning is also easy to implement in Node.JS. To perform such implementation in threadfin-http, you basically create different handler JS file under the different version folders. In other web framework like Express.JS, you would need different routes and different route handler to manage the request.

In the above threadfin-http project, the “api_root” of my project is set to “handler”. In handler folder, I created api/v1 and api/v2 folders. In the 2 folders, I created helloworld_handler.js which are the version 1 and version 2 implementation.

version 1 helloworld_handler.js
version 2 helloworld_handler.js

Header based versioning

The advantage of this implementation is you continue to maintain same URL for the 2 versions of code. In addition, you do not need 2 process handler to keep the 2 implementations in threadfin-http. the 2 implementations are managed through a if condition. It will be easier if you need to maintain common logic within the same JS file.

Result of version 1 hello world
Result of version 2 hello world

As I mentioned earlier, both approaches are viable and it really depends on your requirements. I hope you like my sharing and hope to share more in future !

Originally published at https://my-tech-sharing.blogspot.com on September 22, 2021.

--

--