I think it'll be better to just hard code it, but if you think the url may be dynamic sometimes, you can use JavaScript to handle it.
I don't have an answer to whether it can be done on the server side.
But, I think you should checkout Monica Lent's SEO for Devs course if you want a proper understanding.