circuit

How to Safely Concatenate URLs with Node.js

Learn one of the ways to safely concatenate URLs with Node.js.




Photo by James Harrison on Unsplash

Photo by James Harrison on Unsplash

Recently, in one of my projects, I had pieces of URLs and needed a function to concatenate them and construct a full URL.

Example of the full URL I would like to construct: https://github.com/weikangchia/gitcg

  1. baseUrl: https://github.com

  2. path1 (user of this repository): weikangchia

  3. path2 (name of the repository): gitcg

Initially, I used the ES6 template literals method to construct my full URL.

However, I realized that this method was not safe. If any of my paths happened to include a slash, my fullUrl would have a double slash and become an invalid URL.

After Googling for a while, I tried using 2 Node.js modules:

  1. Url A module that provides utilities for URL resolution and parsing. It provides 2 APIs for working with URLs: a legacy API that is Node.js specific, and a newer API that implements the same WHATWG URL Standard used by web browsers.

  2. Path A module that provides utilities for working with file and directory paths.

And, it worked! I feel that this approach is one of the safer ways to concatenate URLs with Node.js. This approach uses only the built-in modules in Node.js, so fewer jobs to deal with CVEs and maintenance for our production code.

And there we have it. I hope you have found this useful. Thank you for reading. If you enjoyed this article, remember to follow me for more updates!

Feel free to leave comments below if you think there are better ways to concatenate URLs with Node.js.




Continue Learning