In this paper, we consider the optimal dividend policy for an insurance company under a contagious insurance market, where the occurrence of a claim can trigger sequent claims. This clustering effect is modelled by a self-exciting Hawkes process where the intensity of claims depends on its historical path. In addition, we include the concept of bankruptcy to allow the insurance company to operate with a temporary negative surplus. The objective of the management is to obtain the optimal dividend strategy that maximises the expected discounted dividend payments until bankruptcy. The Hamilton–Jacobi–Bellman variational inequalities (HJBVIs) are derived rigorously. When claim sizes follow exponential distributions and the bankruptcy rate is a positive constant, the value function can be obtained based on the Gerber–Shiu penalty function and the optimal dividend barrier can be solved numerically. Finally, numerical examples are demonstrated to show the impact of key parameters on the optimal dividend strategy.