When fetching data from an external API, developers aim to make their code modular, bug-free, and secure. One way to achieve this is by declaring URLs only once and using them throughout the application. As a developer that mainly usees client-side feature of single page appplications, I found the new URL API to be extremely helpful, as it allows me to set an API string and manipulate them throughout the application with ease. I also prefer using the fetch API because I believe its lightweight in nature and efficiency. However, For applications like next JS the fetch API is in beta version, so I was aware that I could use it on the service side. But I did not think too much into the URL(). A deeper look,and a few errors, I found out you cannot use URL() on the server side, it will result in errors.
It turns out that these APIs are exclusive to the browser's environment and are not defined in the Node.js runtime environment. which means if we are making an api request on the frontend on a server-side component, after the code is ran, URL will be undefined. Although these APIs may seem like built-in JavaScript classes, they are actually part of the Web APIs specification and are used in the browser environment. If we think about it..., we never needed to import them from Node.js or any other package, because their functionality was already built into the browser. While this may seem like a minor difference, it is significant.
As for URL api, since you're using a server-side component, there's no need to really worry about users having direct access to your API URLs strings. Because your application is built in the server, then sent to the client side. You could even put your URL string directly in the http request. but, for best practices of declaring all url's once, you can include them in an environment file ".env" or a constant file that holds all your api url strings. like below.
If you're working on a bigger project, with multiple people, I believe the best option would be to build something similar. Using the builder pattern, I believe would make concatenating additional quarry Paramus, or search programs to the URL easier. And if you choose to do this I believe it would be best to just build what you need at the moment and add to the builder as you go anymore.
As for the fetch API, In my opinion, the next best alternative to this is the axios library. It may not be as lightweight in size of the package. However, the size of an HTTP client library should not be the only criteria for choosing it. Axios is feature rich and will allow you to anything you desire.