You can never prevent someone suing you
Your contract with your client is about risk allocation - who assumes the risk and who pays for the risk.
In general, the least cost solution for everybody is that the person who can best manage the risk should assume the risk: many contracts ignore this sensible rule and try to shove risk off on a person who has no chance of dealing with it - the correct solution if that is you is to say "nope" and look for a different client.
Your contract to state what you are going to do and the risks you are going to assume and the price you charge should cover the work and the risk. It is perfectly sensible that you should assume the risk of someone hacking your code because you, not your client, are in the best position to mitigate that risk - the mitigation and the assumption of the residual risk are things you should price and charge for.
It is not sensible that you should assume the risk for subsequent changes to the code and your contract should say this. If your client insists that you do assume this risk (which you cannot manage) you should charge appropriately (i.e. lots) or walk away.
Notwithstanding, your contract gives you no protection against third-parties. For example, if your code causes damage to the site's users or breaches a law (e.g. EU privacy laws). They are not parties to the contract so they will not be suing you under it: they will be suing or prosecuting you under a statute or the common law of negligence (probably).
You can write an indemnity into your contract that if you do get sued then your client assumes that risk - your client will probably expect a hefty discount for assuming that risk. However, even if you have a perfect indemnity in your contract it is of no use to you if your client no longer exists when you get sued. In any event, you cannot claim an indemnity if you commit an offence: if you break the law you pay the fine or do the time. Further, you may have to sue your client to enforce the indemnity.
You can (and should) take out a professional indemnity insurance policy - this passes some of the risks on to your insurer providing that you comply with your insurance contract. An insurer is also responsible for defending any lawsuits against you.
You can also form a corporation and conduct your business through that. In general, your personal assets would not be at risk but if you are personally liable (e.g. for a crime) this will not help.