In my Angular application I have updated some URLs in my project from previously using query string elements like this:
to a route based system similar to this:
This works fine but most of the time except when there’s a product called something like The / Next / Big Thing
So the slashes break the routing as is expected. I’ve encoded the product name using encodeUrlComponent and was going to decode using decodeUrlComponent but I was curious as to whether this is considered safe. The values are going to be the same as when they were query string elements and that was considered safe, so is decodeUrlComponent ok to use here or should I add an extra layer of protection against malicious angles?
I’ve read differing reports on whether decodeUrlComponent is good practice so am looking for some clarity or alternatives if it’s a bad idea.
Why do I need to decode it? Well I’m navigating to a component and using the product name, taken from the URL to populate some data on the component I navigate to. So for example a form field will have the product name pre-populated in it as it was taken from the URL.
Oh. then I think best solution here is to use URL object to create a url and decode it using decodeUrlComponent as you mentioned. If I have access to the backend code, I would validate the title on the server and add constraint to the database to prevent unwanted characters on the title. If I don’t have access to the backend, then encoding and decoding is the only solution for me
URL object to create an encoded url from the title of the product.
const product_url = new URL('The / Next / Big Thing', 'http://www.whatever.com/products')
This will return an encoded URL for use in the Angular router.
When its comes to malicious code, what I would do is prevent inserting them in to the database. That mean, whenever the product is creating, check for suspicious characters like,
/> etc on the server and prevent them from inserting.
I would suggest you to use this library, This decodes strings that were encoded by
encodeURIComponent, without throwing errors on invalid escapes