DEV Community

Julia Shlykova
Julia Shlykova

Posted on

URL path and react-router dynamic segment


I have a project in which usernames go as dynamic segment in react-router route with path=’/users/:userName’ and this fact must lay certain restrictions on these usernames, since they are now parts of URL path. Of course, we can encode userName before using it in the path, but it will deteriorate a user experience, since the point to paste userName in url is to allow user check whose profile he’s viewing. And with multiple % and numbers it’s definitely not the best. So, we better check what we can paste literally in our URL path.

Valid URL path

First of all, we certainly can’t allow / inside our usernames, since it’s used as a separator in URL path.

According to, the path is terminated by the first ? or # character, or by the end of the URL. We can’t use these characters as well.

Also, the path segments . and .., also known as dot-segments, are defined for relative reference within the path name hierarchy. If we set path as '/home/.', we will go to '/home/' and if path is '/home/..' we return to '/'. We shouldn’t allow usernames as a single or double dots.

According to the documentation, A–Z,  a–z,  0–9,  -,  .,  _,  ~,  !,  $,  &,  ',  (,  ),  *,  +,  ,,  ;, =,  :,  @ are all characters that we can use without encoding in the path.

However, many developers stick to only A–Z,  a–z,  0–9,  -, _ and actually that makes sense for usernames :).

Input validation tips

So, what is the best way to validate input? The good practice in web development is to validate input everywhere you can: both the client and server-sides.
For front-end validation we can use input pattern attribute which allows us to define what values can be submitted.
For example, we have following structure:

   <label for="username">Username:</label>
   <input type="text" id="username" />
Enter fullscreen mode Exit fullscreen mode

and we can set input pattern to allow submit only A–Z,  a–z,  0–9,  -, _:

<input type="text" pattern="[\w\-]+" />
Enter fullscreen mode Exit fullscreen mode

Top comments (0)