How to organize routes and endpoints in frontend apps (React, Angular, Vue…) using the sweet-path package. Typescript

Yevhen Kazmirchuk
3 min readApr 3, 2022

What is the best way to organize endpoints or routes? Maybe create a file, for example, endpoints.ts, and create an object as on the picture before:

But, when we had to make an HTTP request to one of these endpoints, we didn't have any mechanisms to replace path parameters (:articleId, or :commentId), so we cannot use such an approach in our app, and we have to use just raw string in request:

That’s bad because usually, we cannot give any guarantees that this endpoint will not be used by any other piece of code in our app.

Also, there are many npm packages that give you API to replace path parameters, but if you forget to pass some of the parameters, you will not receive any errors.

How sweet-path can help you to solve this problem?

First of all, I want to say, that sweet-path is an extremely small library that provides only one thing — the ability to replace path parameters, and in case you forget to pass one of them, you will get an error. Its size is less than 1kb.

Let’s rewrite the example at the very top, using sweet-path:

First of all, we need to install sweet-path:

npm i — save sweet-path

Now, instead of saving just strings inside of articleEndpoints object, we are saving SweetPath instances. To create SweetPath, you have to pass the string into the constructor.

If you are using Typescript, before calling SweetPath, in “<>” you have to specify path parameters inside of the string your pass into SweetPath. if there is more than one parameter, they should be separated by the “|” sign.

To identify the path parameter, it should start from “:”, as in the example.

There are 2 options how to use SweetPath:

  1. To get the original string, you have passed it into the constructor. It’s useful if you want to organize some routings, and you need to have the original URL with path parameters identifiers:

2. To insert path parameters.

There is a method insert, where you have to pass object, with all parameters inside of “<>”. If you will not specify at least one of them, you’ll get an error

If inside of URL you don’t have any path parameters, and you need to use the insert method, you have pass empty object:

More examples and instructions you find in package description on npm:

Thank you for reading!

--

--